我有一个方面,结果如下:

{
    directConfigs: [
        type: "Type A",
        result: {
            priority: 2,
            id: ObjectId('63c6a4b858612f44f37d4771')
        },
        type: "Type B",
        result: {
            priority: 3,
            id: ObjectId('63bd7878f1f085f7d8a6827f')
        }
    ],
    indirectConfigs: [
        type: "Type A",
        result: {
            priority: 1,
            id: ObjectId('627279d3ba7aef5d6418c867')
        },
        type: "Type C",
        result: {
            priority: 5,
            id: ObjectId('63be730bf1f085f7d8a682c8')
        }
    ],
}

从这个结果中,我希望获得在type字段上分组的对象列表.规则是directConfigs优先于indirectConfigs.因此,如果两个数组都具有类型A配置,则我们需要directConfigs中的那个.我已经确保每个类型在每个数组中只能出现一次.结果应该如下所示:

result: [
    {
        type: "Type A",
        result: {
            priority: 2,
            id: ObjectId('63c6a4b858612f44f37d4771')
        }
    },
    {
        type: "Type B",
        result: {
            priority: 3,
            id: ObjectId('63bd7878f1f085f7d8a6827f')
        }
    },
    {
        type: "Type C",
        result: {
            priority: 5,
            id: ObjectId('63be730bf1f085f7d8a682c8')
        }
    }
]

我该怎么做?

推荐答案

一种 Select 是使用$reduce:

db.collection.aggregate([
  {$project: {
      _id: 0,
      result: {
        $reduce: {
          input: "$indirectConfigs",
          initialValue: "$directConfigs",
          in: {$concatArrays: [
              "$$value",
              {$cond: [
                  {$not: {$in: ["$$this.type", "$$value.type"]}},
                  ["$$this"],
                  []
              ]}
          ]}
        }
      }
  }}
])

看看它在playground example号公路上是如何工作的

Mongodb相关问答推荐

MongoDB.ArrayFilters出错:在路径中找不到标识符';elem';的数组筛选器

MongoDB:就地分组嵌套数组的元素

从MongoDB中的嵌套数组中提取找到的值及其索引

当日期和时间在不同键的字符串中时,Mongo 查询过滤今天的数据

嵌套数组 $unwind 和 $group 在 mongoDB 中重新组合在一起

MongoDB聚合多条件

MongoDB 的 Java 语法

在 mongoDB 中存储 java 8 LocalDate

oplog 在独立 mongod 上启用,不适用于副本集

从 MongoDB find() 结果集中识别最后一个文档

MongoDB:设置 Windows 服务

在 MongoDb 中查询小于 NOW 的日期时间值

使用 ObjectId.GenerateNewId() 还是离开 MongoDB 创建一个?

Golang/mgo:如何让 MongoDB 在字段中使用当前时间?

Docker 内部的 Mongo 身份验证

mongo php副本连接非常慢

将数据插入 MongoDB - 没有错误,没有插入

Mongoose 版本控制:when is it safe to disable it?

无法在 mac os 10.9 上安装 mongodb php 驱动程序

无法从 mongodb 中删除集合