首页 > 解决方案 > Mongodb查询没有返回我想要的

问题描述

我正在尝试返回所有最新创建的 appUserID。

Created 是他们制作的最后一条记录的时间戳

db.getCollection('<my collection>').aggregate([{
    '$match': {
        '$and': [
            {
                'companyID': < company ID > 
            },
            {
                'created': {
                    '$gte': < startDate timestamp > 
                }
            },
            {
                'created': {
                    $lt: < endDate timestamp > 
                }
            }
        ]
    }
}, {
    '$project': {
        'appUserID': 1
    }
}, {
    '$group': {
        '_id': '$appUserID',
        'registrationsCount': {
            '$sum': 1
        },

    },

}, {
    '$sort': {
        'registrationsCount': - 1
    }
}])

这当前返回 appuserID 和 registrationCount 并对其进行排序,但我无法返回 appuserID 和最新的时间戳

标签: mongodb

解决方案


发生这种情况是因为您使用投影删除了必填字段:

{
    '$project': {
        'appUserID': 1
    }
}

该指令将清除除 . 之外的所有字段appUserID。为了能够进行最新的时间戳计算,您必须将其保存在聚合管道中:

{
    '$project': {
        'appUserID': 1,
        'created' : 1
    }
}, {
    '$group': {
        '_id': '$appUserID',
        'registrationsCount': {
            '$sum': 1
        },
        'latest': {
            $max: '$created'
        }
    },
}

我使用created了字段,但你可以使用任何你想要的。

结果将如下所示:

{
    "_id" : <some id>,
    "registrationsCount" : <count>,
    "latest" : <some date>
}

推荐阅读