Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb count() of internal array

I have the following MongoDB collection db.students:

/* 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 subjects for a given student. I have a query:

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

that will return the student document. How do I find the count for 'subjects'? Is it doable in a simple query?

like image 657
Marta Avatar asked Nov 19 '14 11:11

Marta


1 Answers

If query will return just one element :

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

For multiple elements in cursor :

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

Do not forget to check existence of subjects either in query or before check .length

like image 182
Mustafa Genç Avatar answered Oct 01 '22 02:10

Mustafa Genç