如何将字段与MongoDB中的阵列进行比较
我有以下文件。我想检索所有地址的文档。
[
{
"name": "star1",
"active": 1,
"address": [
{
"id": 1,
"city": "newyork"
},
{
"id": 2,
"city": "sydney"
}
]
},
{
"name": "star2",
"active": 2,
"address": [
{
"id": 1,
"city": "newyork"
},
{
"id": 2,
"city": "london"
}
]
}
]
我已经写了以下查询,它部分有效,但是它没有返回完整的文档。我不能使用Undind。我们有任何解决方案而无需使用“ Undind”。是否可以仅通过$匹配解决问题
db.collection.aggregate([
{
$unwind: "$address"
},
{
$match: {
$expr: {
$eq: [
"$active",
"$address.id"
]
},
"address.city": "newyork"
}
}
])
I have a documents like below. I want to retrieve all documents whose address.city == "newyork" and address.id == active.
[
{
"name": "star1",
"active": 1,
"address": [
{
"id": 1,
"city": "newyork"
},
{
"id": 2,
"city": "sydney"
}
]
},
{
"name": "star2",
"active": 2,
"address": [
{
"id": 1,
"city": "newyork"
},
{
"id": 2,
"city": "london"
}
]
}
]
I have written below query and it Partially works, But It is not returning complete document. I can't use unwind. Do we have any solution without using "unwind". Is it possible to solve a problem only with $match
db.collection.aggregate([
{
$unwind: "$address"
},
{
$match: {
$expr: {
$eq: [
"$active",
"$address.id"
]
},
"address.city": "newyork"
}
}
])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要匹配整个文档,该文档包含至少一个条目{address.id == active and adverty.city == newyork}以下是一个选项:
解释:
仅匹配具有至少一个在地址数组中的对象的文档== $ active and city ==“ newyork”
playground
> ,更正确的选项如下:
解释:
仅匹配文档至少在数组中具有{id == $ active and active and city ==“ newyork”}或{city ==“ newyork”和id == $ active }
Playground 2
In case you need to match the whole document containing at least one entry having {address.id==active and address.city==newyork } here is an option:
Explained:
Match only documents having at least one object in address array with id==$active and city=="newyork"
Playground
In case we expect different order inside the address objects , the more correct option is as follow:
Explained:
Match only documents having at least one object in array with { id==$active and city=="newyork" } or { city=="newyork" and id==$active }
Playground 2
也许是这样的:
解释:
Playground
Maybe something like this:
Explained:
Playground