How to search in array of object in mongodb

How to search in array of object in mongodb

Asked on January 2, 2019 in MongoDB.
Add Comment


  • 2 Answer(s)

    The best solution:

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

    The $elemMatch is used to allow for more than one component within the same array element.

    For that mongo will look for users with National Medal in some year and some award in 1975s without $elemMatch. but not for users with National Medal in 1975.

    We can see MongoDB $elemMatch Documentation for more info. And then to see Read Operations Documentation for more information about querying documents with arrays.

    Answered on January 2, 2019.
    Add Comment

    To finding the array of particular object to using an $elemMatch.

    db.users.findOne({"_id": id},{awards: {$elemMatch: {award:'Turing Award', year:1977}}})
    
    
    Answered on January 2, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.