gpt4 book ai didi

嵌套数组上的 MongoDB $elemMatch 投影

转载 作者:行者123 更新时间:2023-12-02 03:46:13 24 4
gpt4 key购买 nike

我有一个像这样的集合(摘要)。

    {
"id":"summaryid",
"locations": [
{
"id": "loc1",
"datacenters": [
{
"id": "dc1.1",
"clusters": [
{
"id": "cl1.1",
"servers": [
{
"id": "srvr1.1",
"services": [
{
"id": "srvc1.1"
}
]
}
]
}
]
},
{
"id": "dc1.2",
"clusters": [
{
"id": "cl1.2",
"servers": [
{
"id": "srvr1.2",
"services": [
{
"id": "srvc1.2"
}
]
}
]
}
]
}
]
},
{
"id": "loc2",
"datacenters": [
{
"id": "dc2.1",
"clusters": [
{
"id": "cl2.1",
"servers": [
{
"id": "srvr2.1",
"services": [
{
"id": "srvc2.1"
}
]
}
]
}
]
},
{
"id": "dc2.2",
"clusters": [
{
"id": "cl2.2",
"servers": [
{
"id": "srvr2.2",
"services": [
{
"id": "srvc2.2"
}
]
}
]
}
]
}

]
}
]
}

现在我只想要用于数据中心且 ID 为 dc1.1 的集群。我想为集群排除服务器。

我尝试使用带有 $elemMatch 和投影的查找查询,如下所示。

db.summary.find({}, {"locations": { $elemMatch: { "datacenters._id" : 
"dc1.1" } }, "locations.datacenters.clusters":0,
"locations.datacenters.servers":0, "locations.datacentercount" : 0,
"locations.clustercount" : 0, "locations.servercount" : 0}).pretty()

我仍在获取所有数据中心,而不仅仅是 1 个与 ID 匹配的数据中心。我不确定我是否做对了。

谢谢!

最佳答案

$elemMatch 无法投影嵌套数组元素。

您可以在 3.4 服务器中尝试以下聚合。

使用 $unwind 几次到达嵌套数组并应用 $match 来选择嵌套数组元素。

   db.summary.aggregate([
{
"$match": {
"locations.datacenters._id": "dc1.1"
}
},
{
"$unwind": "$locations"
},
{
"$unwind": "$locations.datacenters"
},
{
"$match": {
"locations.datacenters._id": "dc1.1"
}
},
{
"$project": {
"locations.datacenters.clusters.servers": 0
}
}
])

{"$project": {"locations.datacenters.clusters.servers": 0}} 将删除 servers 字段,同时保留所有其他字段最终输出。

来自文档

If you specify the exclusion of a field other than _id, you cannot employ any other $project specification forms: i.e. if you exclude fields, you cannot also specify the inclusion of fields, reset the value of existing fields, or add new fields.

引用: https://docs.mongodb.com/manual/reference/operator/aggregation/project/#exclude-fields

关于嵌套数组上的 MongoDB $elemMatch 投影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46670813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com