MongoDB 按偶数元素将数组拆分为 N 元素数组 [英] MongoDB split array to N-elements array by even element

查看:34
本文介绍了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 ] }
                }
            }
        }
    }
])

这篇关于MongoDB 按偶数元素将数组拆分为 N 元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆