Ayo*_*b k 4 mongodb nosql mongodb-query aggregation-framework
我有两个集合initiatives和resources:
倡议文件示例:
{
"_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,
},
],
}
Run Code Online (Sandbox Code Playgroud)
和资源文件:
{
"_id" : ObjectId("5c3ddf072430c46dacd75dbc"),
"name" : "Statistician",
"type" : "FUNC",
}
Run Code Online (Sandbox Code Playgroud)
所以我想用参与的总和来返回每个资源。为此,我需要加入这两个集合。
db.resources.aggregate([
{
"$match": { type: "FUNC" }
},
{
"$lookup": {
"from": "initiatives",
"localField": "_id",
"foreignField": "initiatives.resources",
"as": "result"
}
},
])
Run Code Online (Sandbox Code Playgroud)
但首先我需要展开外部字段数组。
预期输出示例:
{
"function" : "Data Manager"
"participation_sum": 50
}
{
"function" : "Statistician"
"participation_sum": 1.5
}
{
"function" : "Supply Manage"
"participation_sum": 0
}
Run Code Online (Sandbox Code Playgroud)
您可以在 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"
}}
])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7617 次 |
| 最近记录: |