2016-04-24 8 views
0

Wie das Maximum von sections.Id in unten Dokument erhalten, wo collection._id = einige ParameterMongoDB Abfrage max von Feld innerhalb Array zu bekommen

{ 
    "_id" : ObjectId("571c5c87faf473f40fd0317c"), 
    "name" : "test 1", 
    "sections" : [ 
     { 
      "Id" : 1, 
      "name" : "first section" 
     }, 
     { 
      "Id" : 2, 
      "name" : "section 2" 
     }, 
     { 
      "Id" : 3, 
      "name" : "section 3" 
     } 
} 

I unter

db.collection.aggregate(
[ 
    { 
     "$match": { 
      "_id": ObjectId("571c5c87faf473f40fd0317c") 
     } 
    }, 
    { 
     "$group" : { 
      "_id" : "$_id", 
      "maxSectionId" : {"$max" : "$sections.Id"} 
     } 
    } 
]); 

versucht haben, aber Anstelle von max int single value gibt es ein Array aller IDs im Sektions-Array zurück.

Weitere gleiche Abfrage, wenn in node.js ausgeführt wird, wird ein leeres Array zurückgegeben.

Antwort

1

Ihre Aggregationsanfrage $unwind für opennig zu "sections" Array ersetzen $ group

fügen Sie Ihre Aggregation Abfrage dieser

brauchen

und Ihre Refactoring Aggregationsanfrage ähnliche

db.collection.aggregate(
[ 
    {$unwind : "$sections"}, 
    { 
     "$match": { 
      "_id": ObjectId("571c5c87faf473f40fd0317c") 
     } 
    }, 
    { 
     "$group" : { 
      "_id" : "$_id", 
      "maxSectionId" : {"$max" : "$sections.Id"} 
     } 
    } 
]); 

und mehr Wissen für $unwind: https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/

0

mit $ Projekt

In the $group stage, if the expression resolves to an array, $max does not traverse the array and compares the array as a whole.

With a single expression as its operand, if the expression resolves to an array, $max traverses into the array to operate on the numerical elements of the array to return a single value [sic]

+0

Projekt mit $ wirft Ausnahme: ungültigen Operator '$ max', Code 15999 –

+0

, welche Version von mongodb sind Sie using ... benutze in diesem Fall unwind, wie von @kakashi hatake gesagt, aber benutze es nach deiner Matchabfrage, um die Anzahl der unveränderten Dokumente zu begrenzen – kryshna

+0

MongoDB Shell Version: 3.0.7. Ich brauche Max aller unbewaffneten Sektionen, aber einer bestimmten collection._id, für die Filter bereits angewendet wird, kann also keinen Filter auf sections.Id anwenden. –

Verwandte Themen