Find document with array that contains a specific value



  • 3 Answer(s)

    favouriteFoods is a simple array of strings, you can try to query that field directly:

    PersonModel.find({ favouriteFoods: "sushi" }, ...);
    

    But I’d also suggest to creating the string array explicit in your schema:

    person = {
        name : String,
        favouriteFoods : [String]
    }
    
    Answered on December 24, 2018.
    Add Comment

    mongodb is don’t have $contains operator

    You can do this below code, The closest analogy to contains that mongo has is $in, using this your query would look like:

    PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);
    
    

     

    Answered on December 24, 2018.
    Add Comment

    For that situation I feel like $all would be more appropriate. If you are looking for person that is into sushi you do:

    PersonModel.find({ favoriteFood : { $all : ["sushi"] }, ...})
    

    For your searching want to filter more like so:

    PersonModel.find({ favoriteFood : { $all : ["sushi", "bananas"] }, ...})
    

    Test this : $in is like OR and $all like AND.

    https://docs.mongodb.com/manual/reference/operator/query/all/

     

    Answered on December 24, 2018.
    Add Comment


  • Your Answer

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