mongodb 使用包含特定值的数组查找文档

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18148166/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:20:54  来源:igfitidea点击:

Find document with array that contains a specific value

mongodbmongoose

提问by Ludwig Magnusson

If I have this schema...

如果我有这个架构...

person = {
    name : String,
    favoriteFoods : Array
}

... where the favoriteFoodsarray is populated with strings. How can I find all persons that have "sushi" as their favorite food using mongoose?

...favoriteFoods数组中填充了字符串。如何使用猫鼬找到所有将“寿司”作为他们最喜欢的食物的人?

I was hoping for something along the lines of:

我希望有以下几点:

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

(I know that there is no $containsin mongodb, just explaining what I was expecting to find before knowing the solution)

(我知道$containsmongodb中没有,只是在知道解决方案之前解释了我期望找到的内容)

回答by JohnnyHK

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

作为favouriteFoods一个简单的字符串数组,您可以直接查询该字段:

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/

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

回答by Alistair Nelson

There is no $containsoperator in mongodb.

$containsmongodb 中没有运算符。

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:

您可以使用 JohnnyHK 的答案,因为它有效。最接近包含 mongo 的类比是$in,使用它您的查询将如下所示:

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

回答by Pobe

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

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

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

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

由于您可能想要过滤更多您的搜索,如下所示:

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

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

$in就像 OR 和$allAND 一样。检查这个:https: //docs.mongodb.com/manual/reference/operator/query/all/

回答by Kfir Erez

In case that the array contains objects for example if favouriteFoodsis an array of objects of the following:

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

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

you can use the following query:

您可以使用以下查询:

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

回答by Jesus Campon

In case you need to find documents which contain NULL elements inside an array of sub-documents, I've found this query which works pretty well:

如果您需要在子文档数组中查找包含 NULL 元素的文档,我发现这个查询非常有效:

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

This query is taken from this post: MongoDb query array with null values

此查询取自这篇文章:MongoDb query array with null values

It was a great find and it works much better than my own initial and wrongversion (which turned out to work fine only for arrays with one element):

这是一个很棒的发现,它比我自己的初始版本和错误版本(结果仅适用于具有一个元素的数组工作正常)要好得多:

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

回答by Amitesh

Though agree with find() is most effective in your usecase. Still there is $match of aggregation framework, to ease the query of a big number of entries and generate a low number of results that hold value to you especially for grouping and creating new files.

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

  PersonModel.aggregate([
            { 
                 "$match": { 
                     $and : [{ 'favouriteFoods' : { $exists: true, $in: [ 'sushi']}}, ........ ]  }
             },
             { $project : {"_id": 0, "name" : 1} }
            ]);
  PersonModel.aggregate([
            { 
                 "$match": { 
                     $and : [{ 'favouriteFoods' : { $exists: true, $in: [ 'sushi']}}, ........ ]  }
             },
             { $project : {"_id": 0, "name" : 1} }
            ]);

回答by gautam

Incase of lookup_food_array is array.

lookup_food_array 是数组。

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

Incase of lookup_food_array is string.

lookup_food_array 的情况是字符串。

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

回答by Mark Ryan Orosa

For Loopback3 all the examples given did not work for me, or as fast as using REST API anyway. But it helped me to figure out the exact answer I needed.

对于 Loopback3,给出的所有示例都不适用于我,或者与使用 REST API 一样快。但它帮助我找出了我需要的确切答案。

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

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

回答by Alingenomen

If you'd want to use something like a "contains" operator through javascript, you can always use a Regular expression for that...

如果您想通过 javascript 使用诸如“包含”运算符之类的东西,您始终可以为此使用正则表达式...

eg. Say you want to retrieve a customer having "Bartolomew" as name

例如。假设您要检索名称为“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);
}

回答by user3027146

I know this topic is old, but for future people who could wonder the same question, another incredibly inefficient solution could be to do:

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

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

This avoids all optimisations by MongoDB so do not use in production code.

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