How do I get the total comments in the collection if my collection looks like this. (not the total comments per post but total for the collection.)
{
_id: 1,
post: 'content',
comments: [
{
name: '',
comment: ''
}
]
}
If I have post A with 3 comments and post B with 5 comments. The result should be 8.
count() method is used to return the count of documents that would match a find() query. The db. collection. count() method does not perform the find() operation but instead counts and returns the number of results that match a query.
If used on a field that contains both numeric and non-numeric values, $sum ignores the non-numeric values and returns the sum of the numeric values. If used on a field that does not exist in any document in the collection, $sum returns 0 for that field. If all operands are non-numeric, $sum returns 0 .
To count the results, you need to use the $group stage and count the documents or do it at the application level. However, per my answer below, there is no need to unwind all of the sub-documents. In mongo shell the result of aggregation query is a cursor object, which has the count() method.
To get stats about MongoDB server, type the command db. stats() in MongoDB client. This will show the database name, number of collection and documents in the database. Output of the command is shown in the following screenshot.
You could use the aggregation framework:
> db.prabir.aggregate(
{ $unwind : "$comments" },
{ $group: {
_id: '',
count: { $sum: 1 }
}
})
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 }
In a nutshell this (temporarily) creates a separate document for each comment and then increments count
for each document.
// Insert a comment
> comment = { name: 'JohnDoe', comment: 'FooBar' }
> db.prabir.update(
{ post: "A" },
{
$push: { comments: comment },
$inc: { numComments: 1 }
}
)
Using the aggregation framework again:
> db.prabir.aggregate(
{ $project : { _id: 0, numComments: 1 }},
{ $group: {
_id: '',
count: { $sum: "$numComments" }
}
})
{ "result" : [ { "_id" : "", "count" : 8 } ], "ok" : 1 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With