2013-02-03 8 views
5

Wie bekomme ich die gesamten Kommentare in der Sammlung, wenn meine Sammlung so aussieht. (Nicht die Gesamt Kommentare per Post, sondern insgesamt für die Sammlung.)Summe der Unterdokumente in einer Sammlung erhalten

{ 
    _id: 1, 
    post: 'content', 
    comments: [ 
     { 
      name: '', 
      comment: '' 
     } 
    ] 
} 

Wenn ich Post A mit 3 Kommentare und Post B mit 5 Kommentare haben. Das Ergebnis sollte 8.

Antwort

12

könnten Sie verwenden die aggregation framework:

> db.prabir.aggregate(
    { $unwind : "$comments" }, 
    { $group: { 
     _id: '', 
     count: { $sum: 1 } 
    } 
}) 
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 } 

In aller Kürze das (vorübergehend) für jeden Kommentar ein separates Dokument erstellt und erhöht dann count für jedes Dokument.


Für eine große Anzahl von Beiträgen und Kommentaren es könnte effizienter sein, den Überblick über die Anzahl der Kommentare zu halten. Immer wenn ein Kommentar hinzugefügt wird, erhöhen Sie auch einen Zähler. Beispiel:

// Insert a comment 
> comment = { name: 'JohnDoe', comment: 'FooBar' } 
> db.prabir.update(
    { post: "A" }, 
    { 
     $push: { comments: comment }, 
     $inc: { numComments: 1 } 
    } 
) 

Mit der Aggregation Rahmen wieder:

> db.prabir.aggregate(
    { $project : { _id: 0, numComments: 1 }}, 
    { $group: { 
     _id: '', 
     count: { $sum: "$numComments" } 
    } 
}) 
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 } 
+0

Ich bin neu in MongoDB. Dieser Code, um eine einfache Zählung zu bekommen ... ist entsetzlich. – otocan

8

Sie die aggregate Methode des aggregation framework dafür verwenden können:

db.test.aggregate(
    // Only include docs with at least one comment. 
    {$match: {'comments.0': {$exists: true}}}, 
    // Duplicate the documents, 1 per comments array entry 
    {$unwind: '$comments'}, 
    // Group all docs together and count the number of unwound docs, 
    // which will be the same as the number of comments. 
    {$group: {_id: null, count: {$sum: 1}}} 
); 

UPDATE

Ab MongoDB 2.6 gibt es eine effizientere Art und Weise zu tun Verwenden Sie dazu den Aggregationsoperator $size, um die Anzahl der Kommentare in jedem Dokument direkt abzurufen:

Verwandte Themen