mongodb - 使用 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"]
}
我试图使用$project
with$reduce
但我仍然不知道如何在特定索引处设置元素。
编辑:values
数组的大小没有预先给出。在示例情况下,它假定为 6,因为最大索引为 5。因此values
,在每个输出文档中都必须与该大小对齐。
解决方案
我假设您想要排序,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 ]
}
}
}
}
}
])
推荐阅读
- sql - oracle查询中的limit和offset
- excel - 当单元格不为空时防止工作簿保存
- javascript - 当鼠标指针进入元素时改变随机数div的位置
- php - 在 XML 中查找节点并获取父注释
- c++ - 多线程程序中可能的竞争条件/未定义行为
- camunda - 您如何配置特定于 Camunda 进程的数据源?
- r - 如何使用 tmap 和 sf 基于特征旋转符号(表示空间点数据)?
- scala - 如何将List作为参数传递给Scala中的对象
- xml - 使用 xsl 流在 XSLT3 中分组,但出现“模板规则不可流”错误
- javascript - 计算 JavaScript 中非 Ascii 字符的字符串计数