gpt4 book ai didi

database - MongoDB:子数组中对象的不同值

转载 作者:搜寻专家 更新时间:2023-10-30 23:26:44 29 4
gpt4 key购买 nike

我有一组这样结构的文档。例如:

{ 'observer': 'machine1', 
'seen': [
{'page1': ['/link1', '/link3']},
{'page2': ['/link4', '/link1']},
}

{ 'observer': 'machine2',
'seen': [
{'page3': ['/link2']},
{'page1': ['/link5']},
}

我正在尝试获取数组中所有不同键和值的列表,按 observer 分组。在理想世界中,它看起来像这样:

{'machine1': ['/link1', '/link3', '/link4'], 'machine2': ['/link2', '/link5'] }

{'machine1': ['page1', 'page2'], 'machine2': ['page1', 'page3']}

我知道我可以使用 $aggregate 和 $group 来获取基于子列表的唯一值,但我不确定如何处理对象列表并获取它们的键和值。

最佳答案

您可以使用以下聚合

db.collection.aggregate([
{ "$unwind": "$seen" },
{ "$addFields": {
"seen": {
"$objectToArray": "$seen"
}
}},
{ "$unwind": "$seen" },
{ "$unwind": "$seen.v" },
{ "$group": {
"_id": "$observer",
"links": { "$addToSet": "$seen.v" }
}}
])

MongoPlayground

如果您同时需要页面链接

db.collection.aggregate([
{ "$unwind": "$seen" },
{ "$addFields": {
"seen": {
"$objectToArray": "$seen"
}
}},
{ "$unwind": "$seen" },
{ "$unwind": "$seen.v" },
{ "$facet": {
"pages": [
{ "$group": {
"_id": "$observer",
"pages": { "$addToSet": "$seen.v" }
}}
],
"links": [
{ "$group": {
"_id": "$observer",
"links": { "$addToSet": "$seen.k" }
}}
]
}}
])

MongoPlayground

如果你需要更多的改进

db.collection.aggregate([
{ "$unwind": "$seen" },
{ "$addFields": {
"seen": {
"$objectToArray": "$seen"
}
}},
{ "$unwind": "$seen" },
{ "$unwind": "$seen.v" },
{ "$facet": {
"pages": [
{ "$group": {
"_id": "$observer",
"pages": { "$addToSet": "$seen.v" }
}}
],
"links": [
{ "$group": {
"_id": "$observer",
"pages": { "$addToSet": "$seen.k" }
}}
]
}},
{ "$project": {
"pages": {
"$map": {
"input": "$pages",
"in": {
"$let": {
"vars": {
"links": {
"$arrayElemAt": [
"$links",
{ "$indexOfArray": ["$links._id", "$$this._id"] }
]
}
},
"in": {
"_id": "$$this._id",
"pages": "$$this.pages",
"links": "$$links.links"
}
}
}
}
}
}},
{ "$unwind": "$pages" },
{ "$replaceRoot": { "newRoot": "$pages" }}
])

MongoPlayground

关于database - MongoDB:子数组中对象的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56106944/

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