tune2fs
tune2fs

Reputation: 7705

How to query for objects stored in an array in a mongoDB

I have the following nested object stored in my mongoDB:

var Appointment = new Schema ({

    students: [{user1:String,user2:String, _id: false}],
});

I now want to query my appointments for a studentName which is stored in the array students either in user1 or user2. But I have no idea how I could achieve that? If it is an array I would use:

    Appointment.find({
        students: {$in: [studentName]}
    }, function(err, appointmentsDb) {
        // do something
    });

Upvotes: 0

Views: 54

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312095

You can use an $or operator and dot notation for this:

Appointment.find({ $or: [
    { 'students.user1': studentName },
    { 'students.user2': studentName }
]}, callback);

Upvotes: 2

Related Questions