繁体   English   中英

mongoose 在嵌套阵列上聚合

[英]mongoose aggregate on a nested array

我有一个具有子数组的架构,并且它的每个元素都引用另一个架构,如下所示:

{
 _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
    },
   ]
}
  • $unwind解构matches数组
  • $lookup与用户集合并在 let 中传递用户 ID,
    • $match userId 条件
    • $project显示必填字段,获取expenses.price总和。价格
  • $unwind解构user数组
  • $group by _id并重建matches数组
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" }
    }
  }
])

操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM