首页 > 解决方案 > 在单个聚合中多次查找后合并 Mongo 文档

问题描述

我一直在尝试合并我的文档结果。这是我的查询和数据

{"_id":"5c21ab13d03013b384f0de26",
"roles":["5c21ab31d497a61195ce224c","5c21ab4ad497a6f348ce224d","5c21ab5cd497a644b6ce224e"],
"agency":"5b4ab7afd6ca361cb38d6a60","agents":["5b4ab5e897b24f1c4c8e3de3"]}

这是查询

  return db.collection('projects').aggregate([
  {
    $match: {
      agents: ObjectId(agent)
    }
  },
  {
    $unwind: "$agents"
  },
  {
    $lookup: {
      from: "agents",
      localField: "agents",
      foreignField: "_id",
      as: "agents"
    }
  },
  {
    $unwind: {
      path: "$roles",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $lookup: {
      from: "roles",
      localField: "roles",
      foreignField: "_id",
      as: "roles"
    }
  },
  {
    $lookup: {
      from: "agencies",
      localField: "agency",
      foreignField: "_id",
      as: "agency"
    }
  }
])

如您所见,项目集合中的条目有两个数组,在对每个条目执行查找之前展开,然后在“代理”字段上执行最终查找。

但是,当我从这个查询中得到结果时,我得到的文档计数等于角色的数量。例如,我正在聚合的项目有 3 个角色和 1 个代理。所以我得到了一个包含 3 个对象的数组,每个角色一个,而不是一个文档,其中角色数组包含所有三个角色。代理数组也有可能具有多个值。

好失落...

标签: arraysmongodbaggregation

解决方案


您不必在$lookup$unwind之前运行。该部分指出:localField

如果您的 localField 是一个数组,您可能需要在管道中添加一个 $unwind 阶段。否则localField和foreignField相等的条件是foreignField: { $in: [ localField.elem1, localField.elem2, ... ] }

所以基本上,如果你不运行$unwindthenroles而不是每个角色的文档,你将得到一个rolesas的数组,ObjectIds替换为第二个集合中的对象数组。

因此,您可以尝试以下聚合:

db.collection('projects').aggregate([
    {
        $match: {
            agents: ObjectId(agent)
        }
    },
    {
        $lookup: {
            from: "agents",
            localField: "agents",
            foreignField: "_id",
            as: "agents"
        }
    },
    {
        $lookup: {
            from: "roles",
            localField: "roles",
            foreignField: "_id",
            as: "roles"
        }
    },
    {
        $lookup: {
            from: "agencies",
            localField: "agency",
            foreignField: "_id",
            as: "agency"
        }
    }
])

推荐阅读