Py学习  »  MongoDB

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

Ayoub k • 5 年前 • 403 次点击  

我有两件收藏品 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,
         },
    ],
}

和A 资源 文件:

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

所以我想把每个都还给你 资源 和之和 参与 是有。为此,我需要加入这两个系列。

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
}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30813
 
403 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Anthony Winzlet
Reply   •   1 楼
Anthony Winzlet    5 年前

您可以将下面的聚合与MongoDB一起使用 三点六 及以上

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"
  }}
])