如果我有这种图式。

person = {
    name : String,
    favoriteFoods : Array
}

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

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

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

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


当前回答

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

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

您可以使用以下查询:

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

其他回答

如果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);
}

尽管同意find()在您的用例中是最有效的。仍然有$match的聚合框架,以简化大量条目的查询,并生成少量对您有价值的结果,特别是用于分组和创建新文件。

PersonModel.aggregate ([ { " $匹配":{ 和美元:[{favouriteFoods:{$存在:真的,$:['寿司 ']}}, ........]} }, {$project: {"_id": 0, "name": 1}} ]);

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

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

我知道这个话题很老了,但对于未来可能会想知道同样问题的人来说,另一个非常低效的解决方案可能是:

PersonModel.find({$where : 'this.favouriteFoods.indexOf("sushi") != -1'});

这避免了MongoDB的所有优化,所以不要在生产代码中使用。