如果我有这种图式。

person = {
    name : String,
    favoriteFoods : Array
}

... 其中favoriteFoods数组用字符串填充。我怎样用猫鼬找到所有喜欢吃“寿司”的人?

我希望你能说出这样的话:

PersonModel.find({ favoriteFoods : { $contains : "sushi" }, function(...) {...});

(我知道mongodb中没有$contains,只是解释了我在知道解决方案之前希望找到什么)


当前回答

我觉得在这种情况下用$all更合适。如果你正在寻找一个喜欢吃寿司的人,你可以:

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

因为你可能想过滤更多的搜索,像这样:

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

$in是OR, $all是and。检查这个:https://docs.mongodb.com/manual/reference/operator/query/all/

其他回答

如果你需要在子文档数组中查找包含NULL元素的文档,我发现这个查询工作得很好:

db.collection.find({"keyWithArray":{$elemMatch:{"$in":[null], "$exists":true}}})

这个查询来自这篇文章:空值的MongoDb查询数组

这是一个伟大的发现,它比我自己最初的错误版本(原来只适用于只有一个元素的数组)要好得多:

.find({
    'MyArrayOfSubDocuments': { $not: { $size: 0 } },
    'MyArrayOfSubDocuments._id': { $exists: false }
})

如果lookup_food_array是array。

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

如果lookup_food_array是string。

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

如果你想通过javascript使用“contains”操作符,你总是可以使用正则表达式…

如。 假设您想检索一个名称为“Bartolomew”的客户

async function getBartolomew() {
    const custStartWith_Bart = await Customers.find({name: /^Bart/ }); // Starts with Bart
    const custEndWith_lomew = await Customers.find({name: /lomew$/ }); // Ends with lomew
    const custContains_rtol = await Customers.find({name: /.*rtol.*/ }); // Contains rtol

    console.log(custStartWith_Bart);
    console.log(custEndWith_lomew);
    console.log(custContains_rtol);
}

对于Loopback3,所有给出的例子都不适合我,或者无论如何都不如使用REST API快。但它帮助我找到了我需要的确切答案。

{"where":{"arrayAttribute":{"all":[String]}}}

我觉得在这种情况下用$all更合适。如果你正在寻找一个喜欢吃寿司的人,你可以:

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

因为你可能想过滤更多的搜索,像这样:

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

$in是OR, $all是and。检查这个:https://docs.mongodb.com/manual/reference/operator/query/all/