首页 > 解决方案 > MongoDB 在调用字符串中与 int 进行比较

问题描述

我有一个 MongDB 集合,其中我的文档将日期存储为如下字符串:

"data": {
    "type": "MatchData",
    "matchId": "5b34f2d527f0d904f8ee4bbf",
    "groupId": "5b2a032ffc37de04f30dc412",
    "leaderboardId": "5b2a0387fc37de04f30e149d",
    "matchTitle": "",
    "date": "20180628144304"
}

如您所见,日期保存为字符串,但我希望能够找到日期早于当前日期的所有记录:

var currDate = 20180928000000
dbCollection('matches').find( { "groupId": groupId, "$lt": {"date": currDate} } );

当前示例不起作用,因为 currDate 是整数并且文档中的日期是字符串!?如何在查询中使用 parseInt 或有其他方法?

希望提前帮助和感谢:-)

标签: javascriptmongodb

解决方案


您可以将输入参数转换currDate为字符串

var currDate = "20180928000000"
dbCollection('matches').find({ "groupId": groupId, "$lt": { "date": currDate } })

或者如果您使用的是4.0

那么你可以使用$toInt聚合运算符

dbCollection('matches').find({
  "groupId": groupId,
  "$expr": { "$lt": [{ "$toInt": "$date" }, currDate]}
})

推荐阅读