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


当前回答

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

其他回答

以ISO日期格式保存created_at日期,然后使用$gte和$lte。

db.connection.find({
    created_at: {
        $gte: ISODate("2010-05-30T18:47:00.000Z"),
        $lte: ISODate("2010-05-30T19:00:00.000Z")
    }
})

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

但是,当您检索日期时,可能会非常混乱,因为客户端驱动程序将实例化一个带有自己本地时区的日期对象。mongo控制台中的JavaScript驱动程序肯定会做到这一点。

所以,如果你关心你的时区,那么确保你知道当你拿回来的时候它应该是什么。这对于查询不应该有太大的影响,因为它仍然等同于相同的int(64),不管你的日期对象在哪个时区(我希望如此)。但我肯定会用实际的日期对象(而不是字符串)进行查询,并让驱动程序做它的事情。

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

澄清。重要的是要知道:

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

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

var inputDate = new Date(myDate.toISOString());
MyModel.find({
    'date': { $lte: inputDate }
})
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`) ]
                        },
                    ]
                 }
              }
           }
        }
     }
])