代码之家  ›  专栏  ›  技术社区  ›  Tom

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

  •  315
  • Tom  · 技术社区  · 14 年前

    {
    "_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
    }
    

    如何编写检查 找到18:47到19:00之间的所有物体?我是否需要更新我的文档以便以特定格式存储日期?

    11 回复  |  直到 9 年前
        1
  •  732
  •   Dinei Ahmad Yones    8 年前

    Querying for a Date Range (Specific Month or Day) 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
  •  41
  •   arcseldon    10 年前

    • 是的,您必须传递一个Javascript日期对象。
    • 是的,它必须是ISODate友好的
    • 是的,根据我的工作经验,你需要把日期调整到ISO
    • 是的,处理日期通常是一个乏味的过程,mongo也不例外

    下面是一段代码,我们在其中进行了一些日期操作,以确保Mongo(这里我使用的是mongoose模块,希望其日期属性小于(早于)作为myDate param给定的日期的行的结果)能够正确处理它:

    var inputDate = new Date(myDate.toISOString());
    MyModel.find({
        'date': { $lte: inputDate }
    })
    
        3
  •  22
  •   Anton Tarasenko Jace Browning    6 年前

    pymongo

    在Python中查找两个日期之间的对象 收藏 posts (基于 tutorial ):

    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

        4
  •  20
  •   Ben Smith    14 年前

    MongoDB实际上将日期的毫秒存储为int(64),如 http://bsonspec.org/#/specification

        5
  •  17
  •   aldoWan Owen    7 年前
    db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();
    

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

        6
  •  11
  •   sɐunıɔןɐqɐp Zmey    6 年前

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

    db.CollectionName.find({"whenCreated": {
        '$gte': ISODate("2018-03-06T13:10:40.294Z"),
        '$lt': ISODate("2018-05-06T13:10:40.294Z")
    }});
    
        7
  •  11
  •   Tính Ngô Quang    5 年前

    与一起使用 Moment.js 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) { ... });
    
        8
  •  5
  •   KARTHIKEYAN.A    5 年前

    $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")}})
    
        9
  •  3
  •   ZacharyST    9 年前

    为什么不把字符串转换成YYYYMMDDHHMMSS格式的整数呢?每一个时间增量都会产生一个更大的整数,您可以对整数进行过滤,而不用担心转换为ISO时间。

        10
  •  3
  •   José Pablo Ceballos    4 年前
    db.collection.find({$and:
      [
        {date_time:{$gt:ISODate("2020-06-01T00:00:00.000Z")}},
         {date_time:{$lt:ISODate("2020-06-30T00:00:00.000Z")}}
       ]
     })
    
    ##In case you are making the query directly from your application ##
    
    db.collection.find({$and:
       [
         {date_time:{$gt:"2020-06-01T00:00:00.000Z"}},
         {date_time:{$lt:"2020-06-30T00:00:00.000Z"}}
      ]
    
     })
    
        11
  •  2
  •   Chris Seymour    10 年前

    将日期转换为GMT时区,因为您正在将它们填充到Mongo中。这样就不会有时区问题。然后在twitter/timezone字段上做一个数学运算,当你把数据拉回来展示的时候。

        12
  •  2
  •   Shredator jeenus    4 年前

    db.getCollection('user').find({
        createdOn: {
            $gt: ISODate("2020-01-01T00:00:00.000Z"),
            $lt: ISODate("2020-03-01T00:00:00.000Z")
        }
    })
    
        13
  •  1
  •   Jitendra    5 年前
    mongoose.model('ModelName').aggregate([
        {
            $match: {
                userId: mongoose.Types.ObjectId(userId)
            }
        },
        {
            $project: {
                dataList: {
                  $filter: {
                     input: "$dataList",
                     as: "item",
                     cond: { 
                        $and: [
                            {
                                $gte: [ "$$item.dateTime", new Date(`2017-01-01T00:00:00.000Z`) ]
                            },
                            {
                                $lte: [ "$$item.dateTime", new Date(`2019-12-01T00:00:00.000Z`) ]
                            },
                        ]
                     }
                  }
               }
            }
         }
    ])
    
        14
  •  0
  •   ayu for u    10 年前

    我按照我的要求尝试了这个模型我需要存储一个日期当以后创建一个对象时我想检索两个日期之间的所有记录(文档) 在我的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()
    

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

    为了检索介于到2个日期之间的数据或文档,我使用了以下查询

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