首页 > 解决方案 > mongodb:按条件获取嵌套数组的元素

问题描述

需要按条件获取嵌套数组的元素。产地收藏:

[
  {
    code: 134,
    bindings: [
      {
        devId: "71156ce8-ac2b-4282-9f5a-10133441057c",
        userIds: ["9d300b89-29c0-45a8-a4d3-019cfc8f1c7b"]
      },
      {
        devId: "ca33efa1-ec27-4ee1-8117-8b8ab29c1790",
        userIds: ["73e5af2f-fe01-41a3-bebd-6bab895cab58"]
      },
      {
        devId: "a03f5fbd-f279-4182-bfb6-33aba9de5751",
        userIds: ["dc0c5e59-ef1a-44b9-843b-a4ea73bbed2e"]
      }
    ]
  }
]

我尝试使用聚合函数:

db.trigger.aggregate([
  { $match: { _id: "134" } },
  { $unwind: "$bindings" },
  { $match: { "bindings.devId": "ca33efa1-ec27-4ee1-8117-8b8ab29c1790" } },
  { $project: { _id: 0, dateset: 1 } },
  { $out: "bindings" }
]);

但它没有给出预期的结果。Сan有人告诉我我做错了什么?

标签: mongodbaggregation-framework

解决方案


您可以尝试以下聚合,$replaceRoot将嵌套文档提升到根级别:

db.collection.aggregate([
    {
        $match: { code: 134 }
    },
    {
        $unwind: "$bindings"
    },
    {
        $match: { "bindings.devId": "71156ce8-ac2b-4282-9f5a-10133441057c" }
    },
    {
        $replaceRoot: { newRoot: "$bindings" }
    }
])

蒙戈游乐场


推荐阅读