如果我有这种图式。

person = {
    name : String,
    favoriteFoods : Array
}

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

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

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

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


当前回答

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

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

您可以使用以下查询:

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

其他回答

有一些方法可以实现这一点。第一个是$elemMatch操作符:

const docs = await Documents.find({category: { $elemMatch: {$eq: 'yourCategory'} }});
// you may need to convert 'yourCategory' to ObjectId

第二个是使用$in或$all操作符:

const docs = await Documents.find({category: { $in: [yourCategory] }});

or

const docs = await Documents.find({category: { $all: [yourCategory] }});
// you can give more categories with these two approaches 
//and again you may need to convert yourCategory to ObjectId

$in是OR, $all是and。欲了解更多细节,请查看此链接:https://docs.mongodb.com/manual/reference/operator/query/all/

第三个是by aggregate()函数:

const docs = await Documents.aggregate([
    { $unwind: '$category' },
    { $match: { 'category': mongoose.Types.ObjectId(yourCategory) } }
]};

使用aggregate(),在类别数组中只能获得一个类别id。

我从我的项目中得到这些代码片段,我必须找到具有特定类别/类别的文档,所以你可以根据你的需要轻松地定制它。

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

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

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

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

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

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

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

我觉得在这种情况下用$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/

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

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