Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.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
Node.js 如何从Mongodb中集合内的数组中提取分组结果_Node.js_Mongodb_Aggregation Framework - Fatal编程技术网

Node.js 如何从Mongodb中集合内的数组中提取分组结果

Node.js 如何从Mongodb中集合内的数组中提取分组结果,node.js,mongodb,aggregation-framework,Node.js,Mongodb,Aggregation Framework,我正在使用Foursquare API,在后端使用NodeJS和Mongodb。我将所有用户信息和签入历史记录存储在一个集合中。因此,该系列与此类似: { _id: ..., foursquareId: ... personalInfo: {}, checkins: [ { id: ..., createdAt: 123456789 //Seconds since epoch>,

我正在使用Foursquare API,在后端使用NodeJS和Mongodb。我将所有用户信息和签入历史记录存储在一个集合中。因此,该系列与此类似:

{
    _id: ...,
    foursquareId: ...
    personalInfo: {},
    checkins: [
        {
            id: ...,
            createdAt: 123456789  //Seconds since epoch>,
            venue: {},
            ...
        },
        {
            id: ...,
            createdAt: 123456789  //Seconds since epoch>,
            venue: {},
            ...
        },
        ...
    ]
} 
对于这个问题,我只对checkins数组感兴趣。我需要按月份和年份返回一份签入数量列表,但我不确定哪种方法是最好的方法。我认为结果会是这样的:(但我并不完全相信)


我对前端接收信息的方式不感兴趣我想知道在mongodb中是否可以这样做,因为我在他们的文档或任何其他示例中都找不到这样做的方法。否则,我可能需要在前端执行此操作(这不是一个好主意…因此我可以在这个阵列上获得大约7k或更多的结果…。

使用聚合框架应该可以满足您的需要

db.collectionName.aggregate([
{$unwind:'$checkins'},
{
    $project: {
        id: 1,
        'checkins.createdAt' : 1, 
        newDate : {
            $add : [ new Date(0), {
                $multiply : [ "$checkins.createdAt", 1000 ]
            }]
        }
    }
},
{$project : {
    year: {$year: "$newDate"},
    month: {$month: "$newDate"}
}},
{$group: {_id:{year:"$year", month:"$month"}, count:{$sum:1}}},
{$group: {_id:{year:"$_id.year"}, monthTotals: { $push:  { month: "$_id.month", count: "$count" } }}}
])
这将生成如下文档:

{ 
    "_id" : {
        "year" : NumberInt(2016)
    }, 
    "monthTotals" : [
        {"month" : NumberInt(1),"count" : NumberInt(2)}
        {"month" : NumberInt(2),"count" : NumberInt(3)}
    ]
}
第二步(第一个$project步骤)可能需要根据日期自历元值的存储方式进行调整,但这通常会满足您的需要


如果不对结果进行一些后处理,就无法获得与您所概述的完全相同的数据,但它应该足够简单,可以修改结果。

谢谢@anztenney。这绝对是一条路要走。日期(存储为字符串,我在使用parseInt时遇到问题)出现了一些奇怪的情况,但我会自己处理。如果您需要帮助,请在注释中发布格式。
{ 
    "_id" : {
        "year" : NumberInt(2016)
    }, 
    "monthTotals" : [
        {"month" : NumberInt(1),"count" : NumberInt(2)}
        {"month" : NumberInt(2),"count" : NumberInt(3)}
    ]
}