简体   繁体   English

MongoDB 合并来自不同集合的两个聚合

[英]MongoDB merge two aggregations from different collections

I am new to backend and MongoDB so forgive me if my question sounds stupid.我是后端和 MongoDB 的新手,所以如果我的问题听起来很愚蠢,请原谅我。

I have two collections of offers and products detailed below我有以下详细介绍的两个优惠产品系列

Products产品

[
  {
    "name": "product #1",
    "place": "place ID"
  },
  {
    "name": "product #2",
    "place": "place ID"
  },
  {
    "name": "product #3",
    "place": "place ID"
  }
]

Offers优惠

[
  {
    "name": "offer #1",
    "place": "place ID"
  },
  {
    "name": "offer #2",
    "place": "place ID"
  },
  {
    "name": "offer #3",
    "place": "place ID"
  }
]

so my target is to merge the two aggregations of these two collections and get output similar to this one所以我的目标是合并这两个集合的两个聚合并获得与此类似的输出

[
  {
    "name": "offer #1",
    "place": "place ID",
    "type": "offer"
  },
  {
    "name": "product #1",
    "place": "place ID",
    "type": "product"
  },
  {
    "name": "offer #2",
    "place": "place ID",
    "type": "offer"
  },
  {
    "name": "offer #3",
    "place": "place ID",
    "type": "offer"
  },
  {
    "name": "product #2",
    "place": "place ID",
    "type": "product"
  },
  {
    "name": "product #3",
    "place": "place ID",
    "type": "product"
  }
]

should I aggregate on the product and offer collections or aggregate on place and group the result.我应该在产品上聚合并提供集合还是在地方聚合并对结果进行分组。

You can try,你可以试试,

  • $facet to add all products in a array and add type field $facet将所有产品添加到数组中并添加类型字段
  • $lookup with offers $lookup提供优惠
  • $project to add type field in offers $map through and concat both product and offer using $concatArrays $project在商品中添加类型字段$map through 并使用$concatArrays产品和$concatArrays
  • $unwind deconstruct final array $unwind解构最终数组
  • $replaceRoot to replace final object in root $replaceRoot替换 root 中的最终对象
db.product.aggregate([
  {
    $facet: {
      product: [
        { $addFields: { type: "product" } }
      ]
    }
  },
  {
    $lookup: {
      from: "offer",
      as: "offer",
      pipeline: []
    }
  },
  {
    $project: {
      final: {
        $concatArrays: [
          "$product",
          {
            $map: {
              input: "$offer",
              in: { $mergeObjects: ["$$this", { type: "offer" }] }
            }
          }
        ]
      }
    }
  },
  { $unwind: "$final" },
  { $replaceRoot: { newRoot: "$final" } }
])

Playground操场

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

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