2017-02-23 8 views
0

Dies ist meine Mungo Sammlungsdaten:Scheibe im Array funktioniert nicht?

 { 
      "ShopId" : "439", 
      "productName" : "veg", 
      "productCategory" : "meals", 
      "mrp" : "38 " 

     }, 
     { 
     "ShopId" : "439", 
      "productName" : "non-veg", 
      "productCategory" : "meals", 
      "mrp" : "380 " 
      },{....} 

Abfrage

db.getCollection('ProductDetails').aggregate(
    [{ "$match": { "ShopId": "439" } },{"$group": {"_id": "$productCategory", "count": { "$sum": 1 }, 
    "products": {"$push":{"productname": "$productName"}}}}, 
    {"$group": {"_id": null, "productList": {"$push": {"categoryname": "$_id", "productcount": "$count", 
     "products": "$products"}}}},{$project:{products:{$slice:["$productList.products",2]}}}]) 

Ausgang:

{ 
    "_id" : null, 
    "productList" : [ 
     { 
      "categoryname" : "meals", 
      "productcount" : 8.0, 
      "products" : [ 
       { 
        "productname" : "non veg" 
       }, 
       { 
        "productname" : "veg" 
       }, 
       { 
        "productname" : "c" 
       }, 
       { 
        "productname" : "d" 
       }, 
       { 
        "productname" : "df" 
       }, 
       { 
        "productname" : "dfr" 
       }, 
       { 
        "productname" : "qe" 
       }, 
       { 
        "productname" : "as" 
       } 
      ] 
     } 
    ] 
} 

erwartete Ausgabe:

Ich möchte die Anzahl der Produkte auf 2.But beschränken, statt dass alle Produkte angezeigt werden.

{ 
    "_id" : null, 
    "productList" : [ 
     { 
      "categoryname" : "meals", 
      "productcount" : 8.0, 
      "products" : [ 
       { 
        "productname" : "non veg" 
       }, 
       { 
        "productname" : "veg" 
       } 
       ] 
     } 
    ] 
} 

Antwort

1

Ersetzen Sie Ihre $project Bühne mit unten.

{$project:{products:{$slice:[{$arrayElemAt:["$productList.products", 0]},2]}}} 

Ihre Produkte sind Array von Arrays.

"products": [ 
    [{ 
    "productname": "veg" 
    }, { 
    "productname": "non-veg" 
    }] 
] 

$arrayElemAt mit 0 die innere Anordnung auswählen und Sie $slice die Produkte begrenzen können.

+0

aber Kategoriename und Produktanzahl werden nicht in Ergebnis –

+0

angezeigt, müssen Sie sie zu der $ Projektstufe – Veeram

+0

hinzufügen, ob ich 1 für diese Felder in $ Projekt setzen muss? –

0

Ich glaube, Sie werden mit dem $slice falsche Funktion: Wie ich in diesem Beitrag erwähnt:

Find a value in array

Die Scheibe Funktion nimmt zwei Parameter: Der erste der Anfangsindex ist und die zweite ist die Anzahl der Elemente nach diesem Index. Hier ein Beispiel:

db.collection.find ({}, {_ ID: 0 Produkte: {$ slice: [0,2]})

Diese beiden Elemente aus dem Index nehmen [0] des Arrays. Hoffe, meine Antwort war hilfreich.

Verwandte Themen