0

entsprechen habe ich folgende Dokumentstruktur in mongodbCount Element Subdocument, die ein gegebenes Kriterium

{ 
    "_id" : "123", 
    "first_name" : "Lorem", 
    "last_name" : "Ipsum", 
    "conversations" : { 
      "personal" : [ 
        { 
          "last_message" : "Hello bar", 
          "last_read" : 1474456404 
        }, 
        { 
          "last_message" : "Hello foo", 
          "last_read" : 1474456404 
        }, 
        ... 
      ], 

      "group" : [ 
        { 
          "last_message" : "Hello Everyone", 
          "last_read" : null 
        } 
        ... 
      ] 
    } 
} 

Ich möchte, um die Anzahl der Gespräche von der Subarrays zählen, personal und group wo die last_read null ist, für ein gegebener Benutzer. Bitte wie kann ich das erreichen?

Ich habe versucht:

db.messages.aggregate(
    [ 
    { $match: {"_id":"123", 'conversations.$.last_read': null }}, 
     { 
     $group: { 
      {$size: "$conversations.personal"}, {$size: "$conversations.group"} 
     } 
     } 
    ] 
); 

aber nicht bekommen, er Ausgang gewünscht. Irgendwelche besseren Ideen, bitte?

Antwort

1

Die folgende Abfrage zählt die Anzahl der Unterlagen unter personal und group Arrays, die last_read Wert null haben.

$concatArrays kombiniert mehrere Arrays zu einem einzigen. Es wurde in MongoDB 3.2 eingeführt.

db.collection.aggregate([ 
         { "$match": {"_id":"123", 'conversations.$.last_read': null }}, 
         { "$project":{"messages":{$concatArrays : ["$conversations.personal","$conversations.group"]}}}, 
         { "$unwind": "$messages"}, {$match:{"messages.last_read": null}}, 
         { "$group":{"_id":null, count: {$sum:1}}} 
       ]) 

Probe Ergebnis:

{ "_id" : null, "count" : 3 } 
0

Wie pro Frage sieht es so aus, als ob Sie herausfinden möchten, wo group array last_readnull enthält. Dazu verwenden Sie $in in Aggregation und dann personal Array und zählen Sie das Array. Überprüfen Sie unten Aggregationsanfrage

db.collection.aggregate({ 
    "$match": { 
     "conversations.group.last_read": { 
      "$in": [null] 
     } 
    } 
}, { 
    "$unwind": "$conversations.personal" 
}, { 
    "$group": { 
     "_id": "$_id", 
     "personalArrayCount": { 
      "$sum": 1 
     } 
    } 
}) 
Verwandte Themen