【问题标题】:how to push elements in between mongodb aggregate query如何在mongodb聚合查询之间推送元素
【发布时间】:2022-01-11 14:35:05
【问题描述】:

我有这样的文件

[
  {
    "key": "key1",
    "shops": [
      {
        "shopId": "S1",
        "ShopName": "SN1"
      },
      {
        "shopId": "S2",
        "ShopName": "SN2"
      }
    ]
  }
]

我需要编写一个 aggerate 查询,并且我必须将一些静态元素推送到一个数组中

我试过如下

db.collection.aggregate([
  {
    "$match": {
      "key": "key1"
    }
  },
  {
    $group: {
      _id: null,
      "shops": {
        $push: {
          "shopId": "S3",
          "ShopName": "SN3"
        }
      }
    }
  },
  {
    "$unwind": {
      "path": "$shops"
    }
  }
])

我的目标是在“商店”数组中添加新元素并展开文档。例外结果应如下所示

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "key": "key1",
    "shops": {
      "ShopName": "SN1",
      "shopId": "S1"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "key": "key1",
    "shops": {
      "ShopName": "SN2",
      "shopId": "S2"
    }
  },
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "key": "key1",
    "shops": {
      "ShopName": "SN3",
      "shopId": "S3"
    }
  }
]

你能帮帮我吗?提前谢谢你

【问题讨论】:

  • 使用$concatArrays(您不需要$group 阶段 - 而不是$addFields)。

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

检查这个playground

我的方法是添加一个临时字段withStatic,它是shops 和静态元素的组合,然后使用$unwind 解构它,将shops 重新分配给解构的项目,最后从结果中删除withStatic

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多