Title

Wednesday, 4 February 2015

how to find a document with mongodb by two or more mandatory subcondtions


A possible Schema

var UserSchema = new Schema({   name: {type : String},   clubs: [{name: String}, {type : String}, {attending: boolean} ],  })

What I'm trying to do: find users that 'have' clubs of a certain type and with a certain value for attending:

User   .find({ 'clubs.type': 'fightclub', 'clubs.attending': true },   function(err, users){   //users   }

note: both the conditions must be met within a single 'club', it's not enough for the user to have 2 different clubs that each meet a single condition

Answer

That's exactly what the $elemMatch query operator is for:

User.find({ clubs: {$elemMatch: {type: 'fightclub', attending: true }}},   function(err, users){   //users   }

No comments:

Post a Comment