Count subdocuments for each document

I am trying to simply count subdocuments in Mongo for each document.

Easily retrieve documents in a collection using db.users.find().length()

. I want to do something like this for example db.users.projects.find().length()

. How can i do this?

Edit:

As a result, I want to know how many projects each user has ... So something like:

{_id: 123, projects: 4}

Sample user document:

{
   _id:{$oid: 123},
   username: johnsmith,
   projects: [{$oid: 456}, {$oid: 789}]
}

      

+3


source to share


3 answers


Per @ n9code, you will need an aggregation framework. However, you can easily count the sub-documents with $size

:

db.users.aggregate([{
  $project: {
    _id: '$_id',
    totalProjects: { $size: "$projects" }
  }
}]);

      

Which should return something like this:



{ "_id" : ObjectID(...), "totalProjects" : 89 }, ...

      

$ size will return the length of the array projects

for each document and $ project resizes the documents to include totalProjects

in the size of the array projects

.

+3


source


It looks like you might have multiple usernames in your project for example.

{ username: "buzz", projects: [ list of 2 things ] }
{ username: "dan". projects: [ list of 3 things ] }
{ username: "buzz", projects: [ list of 4 things ] }

      

To get the "grand total" of projects for each username

, try the following:



c = db.foo.aggregate([
{$project: {
    "username": 1,
    "n": {$size: "$projects"}
}
}
, 
{$group: {
    "_id": "$username",
    "alln": {$sum: "$n"}
}
}
]);

      

To obtain

{ "_id" : "buzz", "alln" : 6 }
{ "_id" : "dan", "alln" : 3 }

      

0


source


You will need MongoDB here: Aggregation Framework

db.users.aggregate({$unwind: '$projects'}).count()

      

This expands the array field projects

in each document in your collection, which will be the total number of subcategories projects

.

-1


source







All Articles