Hafiz Hanif
Hafiz Hanif

Reputation: 471

How to query nested mongo collection

I have a collection called 'Profiles', and it has a structure like this:

{
_id : XXXXX,
classrooms:{
   owner:[],
   students: [XYSk0,CCD7U],
},
...
}

I want to get profiles that has classrooms.students equals to CCD7U.

I have tried using $elemMatch on the collection publish function, but unsuccessful:

Meteor.publish('StudentsInClassrooms', function(CCD7U){
   return Profiles.find({ classrooms : { $elemMatch :{ students : CCD7U }} });
});

I even tried dot notation, but still unsuccessful:

Meteor.publish('StudentsInClassrooms', function(CCD7U){
   return Profiles.find({ 'classrooms.students' : CCD7U });
});

How to properly query that kind of nested collection?

Upvotes: 0

Views: 35

Answers (2)

TamingofTheShru
TamingofTheShru

Reputation: 111

You should use the "$in" operator for such query.

Profiles.find({ 'classrooms.students' : { $in :['CCD7U'] } } )

Ref: MongoDB documentation; $in

Upvotes: 1

saDanny
saDanny

Reputation: 28

When you normally query something you would do it

Profiles.find( { 'classrooms': 'classroomName' } );

But because your are trying to find something from nested you need to do it like this

Profiles.find( { 'classrooms': { 'students' : CCD7U } } );

Upvotes: 0

Related Questions