MongoDB查询:与当前日期比较的查找查询

14
我想从MongoDB集合中获取当前日期的文档。我的文档看起来像这样:

{ 
    "_id" : ObjectId("55743941789a9abe7f4af3fd"), 
    "msisdn" : "9xxxxxxxxxx", 
    "act_date" : ISODate("2014-11-24T00:00:00Z"), 
    "date" : ISODate("2015-06-07T00:00:00Z"), 
    "recharge" : { "recharge_amt" : 0, "rechargetype" : "WEB" },
    "voice" : { "local_og_mou" : 20, "local_other_mobile_og_mou" : 0, "nld_og_mou" : 0, "nld_other_mobile_og_mou" : 10 }, 
    "gprs" : { "total_access_count" : 1, "total_datavolume_mb" : 42 }, 
    "sms" : { "freesms" : 3, "local_sms_count" : 0, "nat_sms_count" : 0, "inter_sms_count" : 0 } 
}

在您的编辑中要更加清晰明了... - SID --- Choke_de_Code
http://docs.mongodb.org/manual/reference/operator/update/currentDate/ - Dipesh Parmar
请添加您的文档结构以便更清楚地理解。 - Dev
嗨,开发者,以下是数据结构... - Saikumar A
{ "_id" : ObjectId("55743941789a9abe7f4af3fd"), "msisdn" : "9xxxxxxxxxx", "act_date" : ISODate("2014-11-24T00:00:00Z"), "date" : ISODate("2015-06-07T00:00:00Z"), "recharge" : { "recharge_amt" : 0, "rechargetype" : "WEB" }, "voice" : { "local_og_mou" : 20, "local_other_mobile_og_mou" : 0, "nld_og_mou" : 0, "nld_other_mobile_og_mou" : 10 }, "gprs" : { "total_access_count" : 1, "total_datavolume_mb" : 42 }, "sms" : { "freesms" : 3, "local_sms_count" : 0, "nat_sms_count" : 0, "inter_sms_count" : 0 } } - Saikumar A
我们有30天的数据,如何获取当前日期的数据。这里的条件字段是“日期”。 - Saikumar A
5个回答

25

根据你的问题,你想从mongodb集合中获取当天的文档。在mongoDB shell中键入new Date(),它会给你当前日期和时间,而且每次运行同一个new Date()时这个值都会变化,所以你的查询可能像这样:

db.collectionName.find({"start_date":new Date()}).pretty()

但是,我认为这个查询返回的是那些在你的集合中出现过的文档,但是当前相同的Date值可能不会出现在你的文档中,所以在这种情况下,你应该使用以下方法:

db.collectionName.find({"start_date":{"$lte":new Date()}}).pretty()
db.collectionName.find({"start_date":{"$gte":new Date()}}).pretty()

如果您想要使用年、月、日进行精确匹配,那么在$project中使用$year,$month,$dayOfMonth,并结合聚合(aggregation)方法,可以实现如下:

db.collectionName.aggregate({
  "$project": {
    "year": {
      "$year": "$date"
    },
    "month": {
      "$month": "$date"
    },
    "day": {
      "$dayOfMonth": "$date"
    }
  }
}, {
  "$match": {
    "year": new Date().getFullYear(),
    "month": new Date().getMonth() + 1, //because January starts with 0
    "day": new Date().getDate()
  }
})

以上聚合查询将返回与当前日期匹配的文档,例如当前日期的年、月、日。同时将$match替换为

var currentDate = new Date()

 {
  "$match": {
    "year": currentDate.getFullYear(),
    "month": currentDate.getMonth() + 1, //because January starts with 0
    "day": currentDate.getDate()
  }
}

10
如果您正在使用 Mongoose,您可以在模式定义之后包含 timeStamp: true,以获取自动生成的 createdAt 和 updatedAt 字段,这将由 Mongoose 管理。
const itemSchema = mongoose.Schema({
    // Your Schema definition here
}, {
  timestamps: true
})

根据你的情况,你需要将你的时间戳与今天的开始进行比较,即使用 ISO 字符串表示的零点整,如 2019-11-08T00:00:00.000Z,以及一天的结束,即使用 ISO 字符串表示的晚上11:59,如2019-11-08T23:59:59.999Z
下面的代码可以帮助你完成这个操作。

let queryObj = {}
const startOfDay = new Date(new Date().setUTCHours(0, 0, 0, 0)).toISOString()
const endOfDay = new Date(new Date().setUTCHours(23, 59, 59, 999)).toISOString()
    
queryObj.createdAt = {
  $gte: startOfDay, // 2019-11-08T00:00:00.000Z
  $lt: endOfDay // 2019-11-08T23:59:59.999Z
}

let items = item.find(obj)
// new Date().setUTCHours(0, 0, 0, 0) Generates this weird string '1573171200000' which is not a human readable format of TimeStamp
// To convert it into ISO String we have .toISOString() method 

这里使用了mongoose。但是OP没有提到使用mongoose。MongoDB 不会“处理它”。 - Dan Dascalescu
我的错 @DanDascalescu,已更新答案。谢谢。 - Nikhil Bhandarkar

3
你可以使用以下查询来完成此操作。
db.collection.find({"start_date" : { $gte : new ISODate("2015-05-27T00:00:00Z") }});

注意:上述查询将返回大于指定日期的文档。

查找等于另一个日期的日期

db.collection.find({"start_date" : new ISODate("2015-05-27T00:00:00Z") });

0
从MongoDB v5.0+开始,您可以使用$dateTrunc进行仅日期(不包含时间)的比较。与$$NOW进行比较,以获取当前日期的文档。
db.collection.aggregate([
  {
    "$match": {
      $expr: {
        $eq: [
          {
            $dateTrunc: {
              date: "$startDate",
              unit: "day"
            }
          },
          {
            $dateTrunc: {
              date: "$$NOW",
              unit: "day"
            }
          }
        ]
      }
    }
  }
])

Mongo Playground


0
你可以按照以下方式进行简单的表达式匹配:
$match: {
  $expr: {$eq: [{$year: '$start_date'}, {$year: new Date()}]},
  $expr: {$eq: [{$month: '$start_date'}, {$month: new Date()}]},
  $expr: {$eq: [{$day: '$start_date'}, {$day: new Date()}]},
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接