Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

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 an award 'Nation Medal' and must be awarded in the 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 an exact person.

1 Answer

0 votes
by (106k points)

To search in an array of object in MongoDB the right way is to use the following code:-

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Related questions

Browse Categories

...