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 }
Ich bin neu in MongoDB. Dieser Code, um eine einfache Zählung zu bekommen ... ist entsetzlich. – otocan