首页 文章

在两个日期MongoDB之间查找对象

提问于
浏览
301

我一直在玩mongodb中存储推文,每个对象看起来像这样:

{
"_id" : ObjectId("4c02c58de500fe1be1000005"),
"contributors" : null,
"text" : "Hello world",
"user" : {
    "following" : null,
    "followers_count" : 5,
    "utc_offset" : null,
    "location" : "",
    "profile_text_color" : "000000",
    "friends_count" : 11,
    "profile_link_color" : "0000ff",
    "verified" : false,
    "protected" : false,
    "url" : null,
    "contributors_enabled" : false,
    "created_at" : "Sun May 30 18:47:06 +0000 2010",
    "geo_enabled" : false,
    "profile_sidebar_border_color" : "87bc44",
    "statuses_count" : 13,
    "favourites_count" : 0,
    "description" : "",
    "notifications" : null,
    "profile_background_tile" : false,
    "lang" : "en",
    "id" : 149978111,
    "time_zone" : null,
    "profile_sidebar_fill_color" : "e0ff92"
},
"geo" : null,
"coordinates" : null,
"in_reply_to_user_id" : 149183152,
"place" : null,
"created_at" : "Sun May 30 20:07:35 +0000 2010",
"source" : "web",
"in_reply_to_status_id" : {
    "floatApprox" : 15061797850
},
"truncated" : false,
"favorited" : false,
"id" : {
    "floatApprox" : 15061838001
}

如何编写一个检查created_at并在18:47到19:00之间查找所有对象的查询?我是否需要更新文档以便日期以特定格式存储?

11 回答

  • -1

    为什么不将字符串转换为YYYYMMDDHHMMSS形式的整数?然后,每个时间增量都会创建一个更大的整数,您可以对整数进行过滤,而不必担心转换为ISO时间 .

  • 2

    在MongoDB Cookbook中查询日期范围(特定月份或日期)对此事有一个非常好的解释,但下面是我自己尝试的东西,它似乎有效 .

    items.save({
        name: "example",
        created_at: ISODate("2010-04-30T00:00:00.000Z")
    })
    items.find({
        created_at: {
            $gte: ISODate("2010-04-29T00:00:00.000Z"),
            $lt: ISODate("2010-05-01T00:00:00.000Z")
        }
    })
    => { "_id" : ObjectId("4c0791e2b9ec877893f3363b"), "name" : "example", "created_at" : "Sun May 30 2010 00:00:00 GMT+0300 (EEST)" }
    

    根据我的实验,您需要将日期序列化为MongoDB支持的格式,因为以下内容提供了不需要的搜索结果 .

    items.save({
        name: "example",
        created_at: "Sun May 30 18.49:00 +0000 2010"
    })
    items.find({
        created_at: {
            $gte:"Mon May 30 18:47:00 +0000 2015",
            $lt: "Sun May 30 20:40:36 +0000 2010"
        }
    })
    => { "_id" : ObjectId("4c079123b9ec877893f33638"), "name" : "example", "created_at" : "Sun May 30 18.49:00 +0000 2010" }
    

    在第二个例子中没有预期的结果,但仍然有一个得到 . 这是因为进行了基本的字符串比较 .

  • 2

    澄清 . 重要的是要知道:

    • 是的,您必须传递Javascript Date对象 .

    • 是的,它必须是ISODate友好的

    • 是的,根据我的经验,您需要将日期操作为ISO

    • 是的,使用日期通常总是一个单调乏味的过程,而mongo也不例外

    这是一个有效的代码片段,我们做一些日期操作以确保Mongo(这里我使用的是mongoose模块,并希望结果的日期属性小于(之前)作为myDate param给出的日期的行)可以处理它正确:

    var inputDate = new Date(myDate.toISOString());
    MyModel.find({
        'date': { $lte: inputDate }
    })
    
  • 19

    MongoDB实际上将日期的millis存储为int(64),由http://bsonspec.org/#/specification规定

    但是,当您检索日期时,它会变得非常混乱,因为客户端驱动程序将使用其自己的本地时区实例化日期对象 . mongo控制台中的JavaScript驱动程序肯定会这样做 .

    所以,如果你关心你的时区,那么一定要确定你知道它的回归时应该是什么 . 这对于查询来说无关紧要,因为无论你的日期对象在什么时区(我希望),它仍将等同于相同的int(64) . 但我肯定会用实际的日期对象(而不是字符串)进行查询,让驱动程序做它的事情 .

  • 0
    db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();
    

    collection 替换为要执行查询的集合名称

  • 0

    Python和pymongo

    使用集合 posts 中的 pymongo (基于tutorial)在Python中查找两个日期之间的对象:

    from_date = datetime.datetime(2010, 12, 31, 12, 30, 30, 125000)
    to_date = datetime.datetime(2011, 12, 31, 12, 30, 30, 125000)
    
    for post in posts.find({"date": {"$gte": from_date, "$lt": to_date}}):
        print(post)
    

    {"$gte": from_date, "$lt": to_date} 指定 datetime.datetime 类型的范围 .

  • 463

    使用此代码使用 $gte$lt 查找两个日期之间的记录:

    db.CollectionName.find({"whenCreated": {
        '$gte': ISODate("2018-03-06T13:10:40.294Z"),
        '$lt': ISODate("2018-05-06T13:10:40.294Z")
    }});
    
  • 16

    当你把它们塞进Mongo时,将你的日期转换为GMT时区 . 这样就不会出现时区问题 . 然后,当您将数据拉出来进行演示时,只需在twitter / timezone字段上进行数学运算 .

  • 6

    我尝试在这个模型中根据我的要求,我需要存储一个日期,以后创建一个对象我想要检索我的html文件中的两个日期之间的所有记录(文档)我使用以下格式mm / dd / yyyy

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    
    <html>
    <head>
    
        <script>
    //jquery
        $(document).ready(function(){  
        $("#select_date").click(function() { 
        $.ajax({
        type: "post",
        url: "xxx", 
        datatype: "html",
        data: $("#period").serialize(),  
        success: function(data){
        alert(data);
        } ,//success
    
        }); //event triggered
    
        });//ajax
        });//jquery  
        </script>
    
        <title></title>
    </head>
    
    <body>
        <form id="period" name='period'>
            from <input id="selecteddate" name="selecteddate1" type="text"> to 
            <input id="select_date" type="button" value="selected">
        </form>
    </body>
    </html>
    

    在我的py(python)文件中,我按照以下方式将其转换为“iso fomate”

    date_str1   = request.POST["SelectedDate1"] 
    SelectedDate1   = datetime.datetime.strptime(date_str1, '%m/%d/%Y').isoformat()
    

    并保存在我的dbmongo集合中,“SelectedDate”作为我的集合中的字段

    在我查询后使用的2个日期之间检索数据或文档

    db.collection.find( "SelectedDate": {'$gte': SelectedDate1,'$lt': SelectedDate2}})
    
  • 3

    Using with Moment.js and Comparison Query Operators

    var today = moment().startOf('day');
      // "2018-12-05T00:00:00.00
      var tomorrow = moment(today).endOf('day');
      // ("2018-12-05T23:59:59.999
    
      Example.find(
      {
        // find in today
        created: { '$gte': today, '$lte': tomorrow }
        // Or greater than 5 days
        // created: { $lt: moment().add(-5, 'days') },
      }), function (err, docs) { ... });
    
  • 6

    使用 $gte$lte 在mongodb中查找日期数据

    var tomorrowDate = moment(new Date()).add(1, 'days').format("YYYY-MM-DD");
    db.collection.find({"plannedDeliveryDate":{ $gte: new Date(tomorrowDate +"T00:00:00.000Z"),$lte: new Date(tomorrowDate + "T23:59:59.999Z")}})
    

相关问题