Find document with array that contains a specific value

前端 未结 10 1321
猫巷女王i
猫巷女王i 2020-11-22 04:06

If I have this schema...

person = {
    name : String,
    favoriteFoods : Array
}

... where the favoriteFoods array is popula

相关标签:
10条回答
  • 2020-11-22 04:31

    There is no $contains operator in mongodb.

    You can use the answer from JohnnyHK as that works. The closest analogy to contains that mongo has is $in, using this your query would look like:

    PersonModel.find({ favouriteFoods: { "$in" : ["sushi"]} }, ...);
    
    0 讨论(0)
  • 2020-11-22 04:32

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

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

    As you might want to filter more your search, like so :

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

    $in is like OR and $all like AND. Check this : https://docs.mongodb.com/manual/reference/operator/query/all/

    0 讨论(0)
  • 2020-11-22 04:34

    Incase of lookup_food_array is array.

    match_stage["favoriteFoods"] = {'$elemMatch': {'$in': lookup_food_array}}
    

    Incase of lookup_food_array is string.

    match_stage["favoriteFoods"] = {'$elemMatch': lookup_food_string}
    
    0 讨论(0)
  • 2020-11-22 04:40

    As favouriteFoods is a simple array of strings, you can just query that field directly:

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

    But I'd also recommend making the string array explicit in your schema:

    person = {
        name : String,
        favouriteFoods : [String]
    }
    

    The relevant documentation can be found here: https://docs.mongodb.com/manual/tutorial/query-arrays/

    0 讨论(0)
提交回复
热议问题