Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB按偶数元素将数组拆分为N元素数组_Mongodb_Mongodb Query_Aggregation Framework - Fatal编程技术网

MongoDB按偶数元素将数组拆分为N元素数组

MongoDB按偶数元素将数组拆分为N元素数组,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,嗨,根据MongoDB聚合,我有一个问题 我想划分我的日期列表 "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

嗨,根据MongoDB聚合,我有一个问题

我想划分我的日期列表

"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个元素的小数组,如下所示:

"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") 
    ],
    ...
]
是否有可能在聚合中实现这一点

我看到有一个$split,但是可以在字符串上工作。还有$reduce,但它正在减少。

您可以使用
step
参数设置为
2
来生成索引数组。然后,您只需要获得一个由2个元素组成的数组,请尝试:

db.col.aggregate([
    {
        $addFields: {
            checked: {
                $map: {
                    input: { $range: [ 0, { $size: "$checked" }, 2 ] },
                    as: "index",
                    in: { $slice: [ "$checked", "$$index", 2 ] }
                }
            }
        }
    }
])
您可以使用生成
步骤
参数设置为
2
的索引数组。然后,您只需要获得一个由2个元素组成的数组,请尝试:

db.col.aggregate([
    {
        $addFields: {
            checked: {
                $map: {
                    input: { $range: [ 0, { $size: "$checked" }, 2 ] },
                    as: "index",
                    in: { $slice: [ "$checked", "$$index", 2 ] }
                }
            }
        }
    }
])

哇,我刚试过——它很有魅力。谢谢哇,我刚试过——它很有魅力。谢谢