在MongoDB中找到仅嵌套数组字段中允许的预期值的文档
我将从示例开始,因为它更容易为我解释。
[
{
"_id": 100,
"narr": [
{
"field": 1
}
]
},
{
"_id": 101,
"narr": [
{
"field": 1,
},
{
"field": 2
}
]
}
]
目标是与我指定的值确切找到文档,以字段
。
示例:
对于lookup = [1]
使用_id = 100
。
查找文档 对于lookup = [1,2]
与_id = 101
。
查找文档 到目前为止,我想到了(用于[1,2]的第二个示例):
db.col.find(
{
"narr": {
"$all": [
{
"$elemMatch": {
"field": {
"$in": [1, 2]
}
}
}
]
}
}
)
但它还包括_id = 100
的文档。我该如何使其执行严格的匹配?
构建整个数组无法工作,因为每个嵌套结构中都有多个字段。
I'll start with the example as it's easier to explain for me.
[
{
"_id": 100,
"narr": [
{
"field": 1
}
]
},
{
"_id": 101,
"narr": [
{
"field": 1,
},
{
"field": 2
}
]
}
]
Goal is to find document exactly with values specified by me for a field
.
Example:
for lookup = [1]
find document with _id=100
.
for lookup = [1,2]
find document with _id=101
.
So far I came up with (for second example with [1,2]):
db.col.find(
{
"narr": {
"$all": [
{
"$elemMatch": {
"field": {
"$in": [1, 2]
}
}
}
]
}
}
)
But it also includes document with _id=100
. How can I make it perform strict match?
Building whole arrays won't work as there are multiple fields with unknown values in each nested structure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不考虑
字段
和您的输入中的重复,您只需在narr.field.field
上进行查找即可。这就像在数组上执行搜索,并具有field
的值。这是 mongo playground 供您参考。
如果可能发生重复,请尝试使用
$ setequals
。这是 mongo playground 供您参考。
Without considering duplication in the
field
and your input, you can simply do a find onnarr.field
. It is like performing search on an array with values fromfield
.Here is the Mongo playground for your reference.
If duplication may happens, try to use
$setEquals
.Here is the Mongo playground for your reference.