我一直在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对这件事有很好的解释,但下面是我自己try 过的东西,似乎有效.

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相关问答推荐

查找/查找单个深度嵌套文档的多个集合

Mongo 聚合查找 $gte 6 个月前的日期,以DD-MM-YYYY格式存储为字符串

无法通过管理邮箱/密码身份验证注册/登录新用户帐户(类型错误:加载失败)

MongoDB聚合:如何将查找结果放入嵌套数组中?

使用 mgo 从 golang 中的 Mongodb 中 Select 列

你如何在 Kubernetes 上设置 Mongo 副本集?

Mongo 可尾游标与 Redis 发布/订阅

在 Mongoid 中,Date、Time、DateTime 和 TimeWithZone 字段类型有什么区别吗?

如何使用 Node.js 和 mongoose 解决command find requires authentication?

不能在模块外使用 import 语句

如何在 Node.js 中格式化 Mongoose 的日期?

MongoDB Compass 过滤器(查询)

如何在 MongoDB Map-reduce 映射函数中使用变量

为什么我新创建的 mongodb 本地数据库增长到 24GB?

我如何使用 Twitter 的流 api 中的推文并将它们存储在 mongodb 中

如何使用 MongoDB C# 驱动程序有条件地组合过滤器?

'this' 在 Mongoose 预保存挂钩中未定义

如何从mongoose中的对象 ID 获取创建日期?

是否可以在 Mongodb 中的两个数据库之间进行 $lookup 聚合?

AsQueryable 方法是否在新的 Mongodb C# 驱动程序 2.0rc 中离开?