Mongodb count () internal array

I have the following MongoDB db.students collection:

/* 0 */
{
    "id" : "0000",
    "name" : "John"
    "subjects" : [
      {
        "professor" : "Smith",
        "day" : "Monday"  
      },
      {
        "professor" : "Smith",
        "day" : "Tuesday"  
      }
  ]
}

/* 1 */
{
    "id" : "0001",
    "name" : "Mike"
    "subjects" : [
      {
        "professor" : "Smith",
        "day" : "Monday"  
      }
    ]
}

      

I want to find the number of items for a given student. I have a request:

 db.students.find({'id':'0000'})

      

which will return the student's document. How do I find the counter for "items"? Can a simple request be made?

+3


source to share


2 answers


If the query only returns one item:

db.students.find({'id':'0000'})[0].subjects.length;

      

For multiple items in the cursor:



db.students.find({'id':'0000'}).forEach(function(doc) {
    print(doc.subjects.length);
})

      

Remember to check for items in your request or before checking .length

+2


source


You can use the aggregation framework

db.students.aggregate( 
    [ 
        { $match : {'_id': '0000'}}, 
        { $unwind : "$subjects" }, 
        { $group : { _id : null, number : { $sum : 1 } } } 
    ] 
);

      

  • The step $match

    will be filtered based on student _id
  • The stage $unwind

    deconstructs an array of objects for multiple documents.
  • A milestone $group

    is when the counter is done. _id is null because you are only counting for one user and only need to count.


You will have an output like:

{ "result" : [ { "_id" : null, "number" : 187 } ], "ok" : 1 }

      

+1


source







All Articles