在子文档的多个字段上进行Mongo查询 [英] Mongo Query On Multiple Fields Of Sub-Document

查看:52
本文介绍了在子文档的多个字段上进行Mongo查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的收藏集:

Suppose I have a collection like this:

{ "arr" : [ { "name" : "a", "num" : 1 }, { "name" : "a", "num" : 2 } ] },
{ "arr" : [ { "name" : "b", "num" : 1 }, { "name" : "a", "num" : 2 } ] },
{ "arr" : [ { "name" : "b", "num" : 1 }, { "name" : "b", "num" : 2 } ] }

,我想查找所有arr包含name ="b"和num = 2的子文档的文档.

and I want to find all documents who's arr contains a sub-document with a name = "b" and num = 2.

如果我这样查询:

db.collection.find({
    $and: [
        { "arr.name": "b" },
        { "arr.num": 2 }
    ]
});

它将返回集合中的所有文档,因为它们每个都包含一个name为"b"或num为2的子文档.

it will return all documents in the collection because they each contain a sub-document with either a name of "b" or a num of 2.

我也尝试过:

db.collection.find({
    arr: [
        { "name": "b", "num": 2 }
    ]
});

不会引发任何错误,但不会返回任何结果.

which doesn't throw any errors, yet doesn't return any results.

您如何在MongoDB中查询多个子文档字段?

How do you query on multiple sub-document fields in MongoDB?

推荐答案

这实际上是 $elemMatch 运算符即使它经常被滥用.它实质上对数组内部"的每个元素执行查询条件.除非另外明确调用,否则所有MongoDB参数都是和"操作:

This is actually what the $elemMatch operator is for even though it is often misused. It essentially performs the query conditions on each element "within" the array. All MongoDB arguments are an "and" operation unless explicitly called otherwise:

db.collection.find({ "arr": { "$elemMatch": { "name": "b", "num": 2  } } })

如果您只希望匹配的字段而不希望匹配的字段,那么您可能也想在此处投影" 整个文档:

You probably also want to "project" here as well if you are expecting only the matched field and not that whole document:

db.collection.find(
    { "arr": { "$elemMatch": { "name": "b", "num": 2  } } },
    { "arr.$": 1 }
)

最后解释一下为什么第二次尝试不起作用,该查询:

Finally to explain why your second attempt does not work, this query:

db.collection.find({
    "arr": [
        { "name": "b", "num": 2 }
    ]
})

不匹配任何内容,因为没有实际文档中"arr"包含与您的条件完全匹配的单数元素.

Does not match anything because there is no actual document where "arr" contains a singular element exactly matching your conditions.

您的第一个示例失败..:

Your first example failed..:

db.collection.find({
    $and: [
        { "arr.name": "b" },
        { "arr.num": 2 }
    ]
});

因为有几个满足条件的数组元素,而不仅仅是两个条件都适用于同一元素.这就是 $elemMatch 所添加的,并且当您需要多个条件来匹配时,就可以在其中使用它.

Because there are several array elements that satisfy the conditions and this is not just considered that both conditions apply to the same element. That is what $elemMatch adds, and when you need more that one condition to match, then this is where you use it.

这篇关于在子文档的多个字段上进行Mongo查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆