如果我有这种图式。

person = {
    name : String,
    favoriteFoods : Array
}

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

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

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

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


当前回答

mongodb中没有$contains操作符。

你可以使用来自JohnnyHK的答案。与包含mongo的最接近的类比是$in,使用这个你的查询将看起来像:

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

其他回答

如果数组包含对象,例如,如果favoritefoods是以下对象的数组:

{
  name: 'Sushi',
  type: 'Japanese'
}

您可以使用以下查询:

PersonModel.find({"favouriteFoods.name": "Sushi"});

在这段代码中使用populate & $将很有用。

ServiceCategory.find().populate({
    path: "services",
    match: { zipCodes: {$in: "10400"}},
    populate: [
        {
            path: "offers",
        },
    ],
});

如果你想通过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);
}

由于favoritefoods是一个简单的字符串数组,你可以直接查询该字段:

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

但我也建议在你的schema中显式地使用string数组:

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

相关文档可以在这里找到:https://docs.mongodb.com/manual/tutorial/query-arrays/

mongodb中没有$contains操作符。

你可以使用来自JohnnyHK的答案。与包含mongo的最接近的类比是$in,使用这个你的查询将看起来像:

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