MongoDB 按偶数元素将数组拆分为 N 元素数组
问题描述:
我有一个关于 MongoDB 聚合的问题.
Hi i have a question according to MongoDB aggregations.
我想分割我的日期列表
"checked" : [
ISODate("2018-11-01T07:00:00.000+0000"),
ISODate("2018-11-01T15:00:00.000+0000"),
ISODate("2018-11-02T07:00:00.000+0000"),
ISODate("2018-11-02T15:00:00.000+0000"),
ISODate("2018-11-03T07:00:00.000+0000"),
ISODate("2018-11-03T15:00:00.000+0000"),
ISODate("2018-11-04T07:00:00.000+0000"),
ISODate("2018-11-04T15:00:00.000+0000"),
ISODate("2018-12-01T07:00:00.000+0000"),
ISODate("2018-12-01T15:00:00.000+0000"),
ISODate("2018-12-02T07:00:00.000+0000"),
ISODate("2018-12-02T15:00:00.000+0000"),
ISODate("2018-12-03T07:00:00.000+0000"),
ISODate("2018-12-03T15:00:00.000+0000"),
ISODate("2018-12-04T07:00:00.000+0000"),
ISODate("2018-12-04T15:00:00.000+0000")
]
变成这样的 2 元素小数组:
Into 2-elements little arrays like this:
"checked" : [
[
ISODate("2018-11-01T07:00:00.000+0000"),
ISODate("2018-11-01T15:00:00.000+0000")
],
[
ISODate("2018-11-02T07:00:00.000+0000"),
ISODate("2018-11-02T15:00:00.000+0000")
],
[
ISODate("2018-11-03T07:00:00.000+0000"),
ISODate("2018-11-03T15:00:00.000+0000")
],
...
]
有可能在聚合中实现吗?
It is possible in aggregation to achieve that?
我看到有一个 $split 但适用于字符串.还有 $reduce,但它正在减少.
I saw that there is a $split but works on strings. There is also $reduce, but it's reducing.
答
您可以使用 $range 生成索引数组,step
参数设置为 2
.然后你只需要 $slice 来获取 2-元素数组,试试:
You can use $range to generate an array of indexes with step
parameter set to 2
. Then you just need $slice to get an array of 2-element arrays, try:
db.col.aggregate([
{
$addFields: {
checked: {
$map: {
input: { $range: [ 0, { $size: "$checked" }, 2 ] },
as: "index",
in: { $slice: [ "$checked", "$$index", 2 ] }
}
}
}
}
])