Suppose the mongodb document(table) 'users' is
{
_id: 1,
name: {
first: 'John',
last: 'Backus'
},
birth: new Date('Dec 03, 1924'),
death: new Date('Mar 17, 2007'),
contribs: ['Fortran', 'ALGOL', 'Backus-Naur Form', 'FP'],
awards: [
{
award: 'National Medal',
year: 1975,
by: 'NSF'
},
{
award: 'Turing Award',
year: 1977,
by: 'ACM'
}
]
}
// ...and other object(person)s
I want to find the person who has the award 'National Medal' and must be awarded in year 1975 There could be other persons who have this award in different years.
How can I find this person using award type and year. So I can get exact person.
This question is related to
javascript
arrays
node.js
mongodb
express
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
with find
db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})
as explained in above answers Also, to return only one field from the entire array you can use projection
into find. and use $
db.getCollection("sizer").find(
{ awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
{ "awards.$": 1, name: 1 }
);
will be reutrn
{
_id: 1,
name: {
first: 'John',
last: 'Backus'
},
awards: [
{
award: 'National Medal',
year: 1975,
by: 'NSF'
}
]
}
Use $elemMatch to find the array of particular object
db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})
Source: Stackoverflow.com