我一直在mongodb中存储tweets,每个对象看起来是这样的:

{
"_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?我是否需要更新我的文档以使日期以特定的格式存储?


当前回答

使用下面的代码查找两个日期之间的记录,使用$gte和$lt:

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

其他回答

澄清。重要的是要知道:

是的,你必须传递一个Javascript Date对象。 是的,它必须是ISODate友好的 是的,根据我的经验,让这个工作,你需要操纵日期到ISO 是的,处理日期通常是一个乏味的过程,芒果也不例外

下面是一个工作代码片段,在这里我们做了一点日期操作,以确保Mongo(这里我使用的是mongoose模块,并希望结果的行,其日期属性小于(之前)给出的日期myDate参数)可以正确处理:

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

将日期转换为GMT时区,因为您正在将它们填充到Mongo中。这样就不会有时区问题了。然后,当您将数据拉出来表示时,只需在twitter/timezone字段上进行计算。

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`) ]
                        },
                    ]
                 }
              }
           }
        }
     }
])

使用$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")}})

为什么不将字符串转换为YYYYMMDDHHMMSS形式的整数?每增加一个时间就会生成一个更大的整数,您可以对整数进行筛选,而不必担心转换为ISO时间。