如何在MongoDB聚合的输出上获取数组

时间:2018-02-02 19:05:00

标签: node.js mongodb aggregation-framework

我在MongoDB中有文档,如下:

{
    "_id" : ObjectId("5a748c8b178227d602ec9ce8"),
    "dateHour" : ISODate("2018-02-02T16:00:00.000Z"),
    "data" : [ 
        {
            "date" : ISODate("2018-02-02T16:06:35.033Z"),
            "cap" : 437105726836.0
        }, 
        {
            "date" : ISODate("2018-02-02T16:09:25.127Z"),
            "cap" : 437316498502.0
        },
        ...
    ]
}

使用聚合方法(在NodeJS中):

db.getCollection('hourly').aggregate([
    {$match: {}}, 
    {$unwind: "$data"}, 
    {$project: {_id: 0, date: "$data.date", cap: "$data.cap" } }
])

我输出如下:

[
    {
        "date" : ISODate("2018-02-02T16:06:35.033Z"),
        "cap" : 437105726836.0
    },
    {
        "date" : ISODate("2018-02-02T16:09:25.127Z"),
        "cap" : 437316498502.0
    }
]

问题:获得输出的最有效方法是什么:

[
    [ISODate("2018-02-02T16:06:35.033Z"), 437105726836.0],
    [ISODate("2018-02-02T16:09:25.127Z"), 437316498502.0]
]

我可以简单地添加.map(function(item) {return [item.date, item.cap]}),但这是处理大量数据时最有效的方法吗?

3 个答案:

答案 0 :(得分:1)

使用$project$map

尝试$reduce

$地图

db.col.aggregate(
    [
        {$project : {
            _id : 0, 
            data : {$map : {input : "$data", as : "d", in : ["$$d.date", "$$d.cap"]}}
            }
        }
    ]
)

$减少

db.col.aggregate(
    [
        {$project : {
            _id : 0, 
                data : {$reduce : {input : "$data", initialValue : [], in : {$concatArrays : ["$$value", [["$$this.date", "$$this.cap"]]]}}}
            }
        }
    ]
).pretty()

输出

{
    "data" : [
        [
            ISODate("2018-02-02T16:06:35.033Z"),
            437105726836
        ],
        [
            ISODate("2018-02-02T16:09:25.127Z"),
            437316498502
        ]
    ]
}

答案 1 :(得分:0)

根必须是文件,证明:

db.test.aggregate([
    {$unwind: "$data"}, 
    { $replaceRoot: { newRoot: ["$data.date", "$data.cap"] } }
]);
assert: command failed: {
        "ok" : 0,
        "errmsg" : "'newRoot' expression must evaluate to an object, but resulting value was: [null, null]. Type of resulting value: 'array'. Input document: {date: 2018-02-02T16:06:35.033Z, cap: 4.37106e+11}",
        "code" : 40228,
        "codeName" : "Location40228"
} : aggregate failed

但是,您可以将其投影到文档中的数组中:

> db.test.aggregate([
...     {$unwind: "$data"},
... { $replaceRoot: { newRoot: {a:["$data.date", "$data.cap"] } }}
... ])
{ "a" : [ ISODate("2018-02-02T16:06:35.033Z"), 437105726836 ] }
{ "a" : [ ISODate("2018-02-02T16:09:25.127Z"), 437316498502 ] }

答案 2 :(得分:0)

它在投影中。试试这个:

db.getCollection('hourly').find({}, {data: 1}, (err, results) => {
   // manage results here.
});

以防万一我的语法有点偏差,这里是project a new array的MongoDb文档。

我不知道为什么你需要聚合。

为什么不:

{{1}}