Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get total of sub documents in a collection

Tags:

mongodb

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.

like image 986
prabir Avatar asked Feb 03 '13 02:02

prabir


People also ask

How do I count documents in a collection?

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.

How do I sum fields in MongoDB?

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 .

How does MongoDB count subdocuments?

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.

How do I show all files in a collection in MongoDB?

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.


1 Answers

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.


For a large number of posts and comments it might be more efficient to keep track of the number of comments. When ever a comment is added you also increment a counter. Example:
// 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 }
like image 107
Justin Case Avatar answered Oct 18 '22 16:10

Justin Case