How to search in array of object in mongodb

JavascriptArraysnode.jsMongodbExpress

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

Use $elemMatch to find the array of a particular object

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

Solution 3 - Javascript

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 return

{
    _id: 1,
    name: {
        first: 'John',
        last: 'Backus'
    },
    awards: [
        {
            award: 'National Medal',
            year: 1975,
            by: 'NSF'
        }
    ]
}

Solution 4 - Javascript

You can do this in two ways:

  1. ElementMatch - $elemMatch (as explained in above answers)

    db.users.find({ awards: { $elemMatch: {award:'Turing Award', year:1977} } })

  2. Use $and with find

    db.getCollection('users').find({"$and":[{"awards.award":"Turing Award"},{"awards.year":1977}]})

Solution 5 - Javascript

I'm new to MongoDb, I have the same problem that Stennie describes. I tried to query this document in Compass:

    {
    "_id": 1,
    "name": {
        "first": "John",
        "last": "Backus"
    },
    "birth": {
        "$date": "1924-12-02T23:00:00.000Z"
    },
    "death": {
        "$date": "2007-03-16T23:00:00.000Z"
    },
    "contribs": ["Fortran", "ALGOL", "Backus-Naur Form", "FP"],
    "awards": [{
        "award": "National Medal",
        "year": 1975,
        "by": "NSF"
    }, {
        "award": "Turing Award",
        "year": 1977,
        "by": "ACM"
    }]
}

When to run this query:{awards: {$elemMatch: {award:'National Medal', year:1975}}} for this single document, I get the same result:

{
    "_id": 1,
    "name": {
        "first": "John",
        "last": "Backus"
    },
    "birth": {
        "$date": "1924-12-02T23:00:00.000Z"
    },
    "death": {
        "$date": "2007-03-16T23:00:00.000Z"
    },
    "contribs": ["Fortran", "ALGOL", "Backus-Naur Form", "FP"],
    "awards": [{
        "award": "National Medal",
        "year": 1975,
        "by": "NSF"
    }, {
        "award": "Turing Award",
        "year": 1977,
        "by": "ACM"
    }]
}

It is possible to obtain the single element searched for in this way:

{
    "_id": 1,
    "name": {
        "first": "John",
        "last": "Backus"
    },
    "birth": {
        "$date": "1924-12-02T23:00:00.000Z"
    },
    "death": {
        "$date": "2007-03-16T23:00:00.000Z"
    },
    "contribs": ["Fortran", "ALGOL", "Backus-Naur Form", "FP"],
    "awards": [{
        "award": "National Medal",
        "year": 1975,
        "by": "NSF"
    }, {}]

Thank you

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionvcxzView Question on Stackoverflow
Solution 1 - JavascriptLeonid BeschastnyView Answer on Stackoverflow
Solution 2 - JavascriptKARTHIKEYAN.AView Answer on Stackoverflow
Solution 3 - JavascriptMohammad Yaser AhmadiView Answer on Stackoverflow
Solution 4 - JavascriptJoby Wilson MathewsView Answer on Stackoverflow
Solution 5 - JavascriptDiegoView Answer on Stackoverflow