代码之家  ›  专栏  ›  技术社区  ›  phoebus

嵌套数组上的猫鼬聚合

  •  0
  • phoebus  · 技术社区  · 3 年前

    我有一个模式,它有一个子数组,每个元素都引用另一个模式如下:

    {
     _id: "5fed222d806311ec81d6df23"
     someOtherNestedDoc: {
        _id: "abc",
        someOtherField: 10
     },
     matches: [
       {
          _id: "5fed222d806311ec81d6daf3",
          user: "5fed222d806311ec81d6dcf3",
          probability: 10
       },
       {
          _id: "5fed222d806311ec81d6d1f3",
          user: "5fed222d806311ec81d62cf3",
          probability: 20
       },
     ]
    }
    

    我想做一个Mongoose聚合,在其中我查找每个匹配的用户引用,并且只为它项目3个字段,其中2个已经存在,第三个是该模式的数组之和,所以最后,我有这样的结果:

    {
     _id: "5fed222d806311ec81d6df23"
     someOtherNestedDoc: {
        _id: "abc",
        someOtherField: 10
     },
     matches: [
       {
          _id: "5fed222d806311ec81d6daf3",
          user: {
             firstName: "Max",
             lastName: "Mustermann",
             totalExpenses: 100
          },
          probability: 10
       },
       {
          _id: "5fed222d806311ec81d6d1f3",
          user: {
             firstName: "Herbert",
             lastName: "Mustermann",
             totalExpenses: 200
          },,
          probability: 20
       },
     ]
    }
    

    用户看起来像这样:

    {
      _id: "5fed222d806311ec81d6dcf3",
      firstName: "Max",
      lastName: "Mustermann",
      password: "test",
      expenses: [
        {
          _id: 1,
         price: 50
        },
        {
          _id: 2,
         price: 50
        },
       ]
    }
    
    {
      _id: "5fed222d806311ec81d62cf3",
      firstName: "Herbert",
      lastName: "Mustermann",
      password: "test2",
      expenses: [ 
        {
          _id: 3,
         price: 75
        },
        {
          _id: 4,
         price: 125
        },
       ]
    }
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   turivishal    3 年前
    • $unwind 解构 matches 阵列
    • $lookup 在let中收集用户并传递用户id,
      • $match userId条件
      • $project 要显示必填字段,请获取以下值的总和 expenses.price
    • $放松 解构 user 阵列
    • $group 通过 _id 并重建 比赛 阵列
    db.col1.aggregate([
      { $unwind: "$matches" },
      {
        "$lookup": {
          "from": "user",
          let: { userId: "$matches.user" },
          pipeline: [
            { $match: { $expr: { $eq: ["$_id", "$$userId"] } } },
            {
              $project: {
                _id: 0,
                firstName: 1,
                lastName: 1,
                totalExpenses: { $sum: "$expenses.price" }
              }
            }
          ],
          "as": "matches.user"
        }
      },
      { $unwind: "$matches.user" },
      {
        $group: {
          _id: "$_id",
          matches: { $push: "$matches" }
        }
      }
    ])
    

    Playground