如何在MongoDB的嵌套阵列上求发?
受另一个
假设我的文档看起来像:
{
_id: ObjectId("5a934e000102030405000000"),
events: [
{
status: 0,
timestamp: ISODate("2022-05-29T13:26:00Z")
},
{
status: 8,
timestamp: ISODate("2022-05-29T14:41:00Z")
},
{
status: 4,
timestamp: ISODate("2022-05-31T10:13:00Z")
},
{
status: 3,
timestamp: ISODate("2022-05-31T10:18:00Z")
}
]
}
我想夫妇:
{
_id: ObjectId("5a934e000102030405000000"),
couples: [
[
{
mod: 0,
status: 0,
timestamp: ISODate("2022-05-29T13:26:00Z")
},
{
mod: 1,
status: 8,
timestamp: ISODate("2022-05-29T14:41:00Z")
}
],
[
{
mod: 0,
status: 4,
timestamp: ISODate("2022-05-31T10:13:00Z")
},
{
mod: 1,
status: 3,
timestamp: ISODate("2022-05-31T10:18:00Z")
}
]
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于MongoDB版本4.4*,一个选项是将聚合管道与
$降低
,$ mod
,$ filter
和$ zip
:$ ydre
带有$ mod
添加一个新mod
字段到每个项目,带有Value0
每个奇数索引(1, 3,5,...)和值1
偶数索引(2,4,6,...看看它在 playground示例示例
*与较旧的mongodb版本,3.4或更高版本,
$ mod
可以是替换为“手动”mod
计算。Since mongoDB version 4.4*, One option is to use an aggregation pipeline with
$reduce
,$mod
,$filter
and$zip
:$reduce
with$mod
to add a newmod
field to each item, with value0
to each odd index (1, 3, 5,...) and value1
to each even index (2, 4, 6,...)$fiter
into two arrays according to themod
value$zip
these two arrays to one array of couplesSee how it works on the playground example
*With older mongoDB versions, 3.4 or higher, the
$mod
can be replaces with a "manual"mod
calculation.