gpt4 book ai didi

当外部字段是对象数组时的 MongoDB 查找

转载 作者:可可西里 更新时间:2023-11-01 10:08:46 26 4
gpt4 key购买 nike

我有两个集合 initiativesresources:

倡议文档示例:

{
"_id" : ObjectId("5b101caddcab7850a4ba32eb"),
"name" : "AI4CSR",
"ressources" : [
{
"function" : ObjectId("5c3ddf072430c46dacd75dbb"),
"participating" : 0.1,
},
{
"function" : ObjectId("5c3ddf072430c46dacd75dbc"),
"participating" : 5,
},
{
"function" : ObjectId("5c3ddf072430c46dacd75dbb"),
"participating" : 12,
},
{
"function" : ObjectId("5c3ddf072430c46dacd75dbd"),
"participating" : 2,
},
],
}

和一个资源文档:

{
"_id" : ObjectId("5c3ddf072430c46dacd75dbc"),
"name" : "Statistician",
"type" : "FUNC",
}

所以我想返回每个 resource 以及 participating 的总和。为此,我需要加入这两个集合。

db.resources.aggregate([
{
"$match": { type: "FUNC" }
},
{
"$lookup": {
"from": "initiatives",
"localField": "_id",
"foreignField": "initiatives.resources",
"as": "result"
}
},
])

但首先我需要展开外部字段数组。

预期输出示例:

{
"function" : "Data Manager"
"participation_sum": 50
}
{
"function" : "Statistician"
"participation_sum": 1.5
}
{
"function" : "Supply Manage"
"participation_sum": 0
}

最佳答案

您可以在 mongodb 3.6 及更高版本中使用以下聚合

db.resources.aggregate([
{ "$match": { "type": "FUNC" } },
{ "$lookup": {
"from": "initiatives",
"let": { "id": "$_id" },
"pipeline": [
{ "$match": { "$expr": { "$in": ["$$id", "$ressources.function"] } } },
{ "$unwind": "$ressources" },
{ "$match": { "$expr": { "$eq": ["$ressources.function", "$$id"] } } },
{ "$group": {
"_id": "$ressources.function",
"participation_sum": { "$sum": "$ressources.participating" }
}}
],
"as": "result"
}}
])

关于当外部字段是对象数组时的 MongoDB 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54617074/

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