How to search in array of object in mongodb
The right way is:
db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})
$elemMatch
allows you to match more than one component within the same array element.
Without $elemMatch
mongo will look for users with National Medal in some year and some award in the year 1975, but not for users with National Medal in 1975.
See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.
Use $elemMatch
to find the array of a particular object
db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})
You can do this in two ways:
ElementMatch -
$elemMatch
(as explained in above answers)db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })
Use
$and
withfind
db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})