首页 > 解决方案 > 使用 MongoDB 聚合创建一种“表格”投影

问题描述

假设我在 mongodb 聚合的某个阶段中有以下文档:

{
    type: "A",
    value: "A",
    index: 1
},
{
    type: "A",
    value: "B",
    index: 0
},
{
    type: "B",
    value: "a",
    index: 4
},
{
    type: "B"
    value: "b",
    index: 2
},
{
    type: "B",
    value: "c",
    index: 5
}

我想使用可用的聚合阶段(使用 Mongo 4.0 的语法)将它们处理成:

{
    type: "A",
    values: ["B", "A", null, null, null, null]
},
{
    type: "B",
    values: [null, null, "b", null, "a", "c"]
}

我试图使用$projectwith$reduce但我仍然不知道如何在特定索引处设置元素。

编辑:values数组的大小没有预先给出。在示例情况下,它假定为 6,因为最大索引为 5。因此values,在每个输出文档中都必须与该大小对齐。

标签: mongodbaggregation-framework

解决方案


我假设您想要排序,index并且应该有null, null, "b", "a", "c"for type B。然后您可以使用以下聚合:

db.collection.aggregate([
    {
        $sort: { index: 1 }
    },
    {
        $group: {
            _id: null,
            type: { $addToSet: "$type" }
            docs: { $push: "$$ROOT" }
        }
    },
    {
        $unwind: "$type"
    },
    {
        $project: {
            _id: 0,
            type: 1,
            values: {
                $map: {
                    input: "$docs",
                    in: {
                        $cond: [ { $eq: [ "$type", "$$this.type" ] }, "$$this.value", null ]
                    }
                }
            }
        }
    }
])

基本上$addToSet运算符允许您构建一个唯一type值数组,然后可以将其用于$filter

蒙戈游乐场


推荐阅读