【问题标题】:Create a sort of "tabular" projection using MongoDB aggregation使用 MongoDB 聚合创建一种“表格”投影
【发布时间】:2020-07-19 01:37:37
【问题描述】:

假设我在 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"]
}

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

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

【问题讨论】:

  • 你能解释一下你是如何得到处理后的输出的吗? values 数组中的六个元素是如何得到的?
  • @prasad_ 好点 - 我添加了解释

标签: mongodb aggregation-framework


【解决方案1】:

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

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

Mongo Playground

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-04
相关资源
最近更新 更多