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

标签 mongodb datetime twitter mongodb-query

我一直在尝试将推文存储在 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 之间的所有对象?我是否需要更新我的文档以便以特定格式存储日期?

最佳答案

<罢工> 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" }

在第二个示例中,预计不会有结果,但仍然得到了一个结果。这是因为完成了基本的字符串比较。

关于mongodb - 查找两个日期之间的对象 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45607207/

相关文章:

python - 从列表中的元素中提取 url

java - 如何在 Java 中从城市名称中查找国家/地区名称?

json - 有人在 mongodb 中存储原始 SVG 数据吗?

php - MySQL数据库和导入日期问题

python - 将范围时间数据转换为 pandas to_datetime 中的日期时间

sql - 如何用 Doctrine 更改日期时间值的时间部分?

iphone - iOS 5 使用 Twitter API 将照片附加到 Twitter

node.js - MongoDB shell 导出整个数据库

node.js - 蒙古语或蒙古语 native 不支持群组功能?

java - 将 mongoDB 查询转换为 Java(与排序不同)