How to search in array of object in mongodb


Question

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 award 'Nation 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.

1
177
12/6/2017 10:22:00 AM

Accepted Answer

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 1975s, 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.

316
6/9/2017 3:24:05 PM

Use $elemMatch to find the array of particular object

db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon