一对多 MongoDB 查找项目请求字段

One to Many MongoDB lookup with project req fields

我有两个集合的一对多关系,比如 A 到 B。我怎样才能在一个文档中为每个 ID 显示所需的输出。 例如,我有

/*Collection A*/
{
    "a_Id": "abc",
        "name": "xyz",
        "age": 5
}       

...//其他文档

/*Collection B*/
{
    "b_id": "abc",
    "FeeAmount": 800000,
    "invoiceNumber": "A10",
    "Date": "2021-10-29T00:00:00.000+04:00",
    "PaidAmount": 200000
},
{
    "b_id": "abc",
    "FeeAmount": 90,
    "invoiceNumber": "A20",
    "Date": "2021-10-29T00:00:00.000+04:00",
    "PaidAmount": 20
}

//...其他文档针对不同的 id 多个,例如 abc1、abc2

如何根据id查找后得到下面的输出? 每个 id 一个文档。

    /*Desired OutPut*/
//Document 1
    {
       "name": "xyz",
        "age": 5
       "availableLimitAmount": 800000,
      "FeeAmount": 800000,
        "invoiceNumber": "A10",
        "Date": "2021-10-29T00:00:00.000+04:00",
        "PaidAmount": 200000
    },
    {
        "name": "xyz",
         "age": 5
        "FeeAmount": 90,
        "invoiceNumber": "A20",
        "Date": "2021-10-29T00:00:00.000+04:00",
        "PaidAmount": 20
    }
//Document 2
 {
       "name": "qwe",
        "age": 50
       "availableLimitAmount": 20000,
      "FeeAmount": 40000,
        "invoiceNumber": "B10",
        "Date": "2021-1-1T00:00:00.000+04:00",
        "PaidAmount": 1000
    },
    {
        "name": "qwe",
         "age": 50
        "FeeAmount": 40,
        "invoiceNumber": "B20",
        "Date": "2021-2-2T00:00:00.000+04:00",
        "PaidAmount": 500
    }
  1. 使用 $lookup 运算符连接两个集合 AB
  2. 执行$unwind操作以“传播”结果。
  3. $project随心所欲。

所以试试这个:

db.A.aggregate([
    {
        $lookup: {
            from: "B",
            localField: "a_Id",
            foreignField: "b_id",
            as: "B"
        }
    },
    { $unwind: "$B" },
    {
        $project: {
            "_id": 0,
            "name": "$name",
            "age": "$age",
            "FeeAmount": "$B.FeeAmount",
            "invoiceNumber": "$B.invoiceNumber",
            "Date": "$B.Date",
            "PaidAmount": "$B.PaidAmount",
        }
    }
]);

这里是 working solution 如何实现这一点。

db.coll1.aggregate([
  {
    $lookup: {
      localField: "a_Id",
      from: "coll2",
      foreignField: "b_id",
      as: "data",
      
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          "$data"
        ]
      }
    }
  },
  {
    $project: {
      "data": 0
    }
  }
])

已更新

db.coll1.aggregate([
  {
    $lookup: {
      localField: "a_Id",
      from: "coll2",
      foreignField: "b_id",
      as: "data",
      
    }
  },
  {
    $unwind: "$data"
  },
  {
    $replaceRoot: {
      "newRoot": {
        "$mergeObjects": [
          "$$ROOT",
          "$data"
        ]
      }
    }
  },
  {
    $project: {
      "data": 0
    }
  },
  {
    $group: {
      _id: "$a_Id",
      data: {
        $push: "$$ROOT"
      }
    }
  }
])