查找两个日期之间的对象 MongoDB
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2943222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find objects between two dates MongoDB
提问by Tom
I've been playing around storing tweets inside mongodb, each object looks like this:
我一直在玩在 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
}
How would I write a query which checks the created_atand finds all objects between 18:47 and 19:00? Do I need to update my documents so the dates are stored in a specific format?
我将如何编写一个查询来检查created_at并查找 18:47 到 19:00 之间的所有对象?我是否需要更新我的文档以便日期以特定格式存储?
回答by ponzao
Querying for a Date Range (Specific Month or Day)in the MongoDB Cookbookhas a very good explanation on the matter, but below is something I tried out myself and it seems to work.
MongoDB Cookbook中的Querying for a Date Range (Specific Month or Day)对这个问题有很好的解释,但下面是我自己尝试过的,它似乎有效。
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)" }
Based on my experiments you will need to serialize your dates into a format that MongoDB supports, because the following gave undesired search results.
根据我的实验,您需要将日期序列化为 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" }
In the second example no results were expected, but there was still one gotten. This is because a basic string comparison is done.
在第二个示例中,没有预期的结果,但仍然得到了一个。这是因为完成了基本的字符串比较。
回答by arcseldon
To clarify. What is important to know is that:
澄清。重要的是要知道:
- Yes, you have to pass a Javascript Date object.
- Yes, it has to be ISODate friendly
- Yes, from my experience getting this to work, you need to manipulate the date to ISO
- Yes, working with dates is generally always a tedious process, and mongo is no exception
- 是的,您必须传递一个 Javascript Date 对象。
- 是的,它必须是 ISODate 友好的
- 是的,根据我的经验,您需要将日期操作为 ISO
- 是的,处理日期通常总是一个乏味的过程,mongo 也不例外
Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo (here i am using mongoose module and want results for rows whose date attribute is less than (before) the date given as myDate param) can handle it correctly:
这是一个工作代码片段,我们在其中进行了一些日期操作以确保 Mongo(这里我使用的是 mongoose 模块并希望日期属性小于(之前)作为 myDate 参数给出的日期的行的结果)可以处理它正确:
var inputDate = new Date(myDate.toISOString());
MyModel.find({
'date': { $lte: inputDate }
})
回答by Ben Smith
MongoDB actually stores the millis of a date as an int(64), as prescribed by http://bsonspec.org/#/specification
MongoDB 实际上将日期的毫秒数存储为 int(64),如http://bsonspec.org/#/specification 所述
However, it can get pretty confusing when you retrieve dates as the client driver will instantiate a date object with its own local timezone. The JavaScript driver in the mongo console will certainly do this.
但是,当您检索日期时,它会变得非常混乱,因为客户端驱动程序将使用自己的本地时区实例化日期对象。mongo 控制台中的 JavaScript 驱动程序肯定会这样做。
So, if you care about your timezones, then make sure you know what it's supposed to be when you get it back. This shouldn't matter so much for the queries, as it will still equate to the same int(64), regardless of what timezone your date object is in (I hope). But I'd definitely make queries with actual date objects (not strings) and let the driver do its thing.
所以,如果你关心你的时区,那么确保你知道当你回来时它应该是什么。这对于查询来说并不重要,因为它仍然等同于相同的 int(64),无论您的日期对象位于哪个时区(我希望)。但我肯定会使用实际日期对象(而不是字符串)进行查询,并让驱动程序完成它的工作。
回答by Anton Tarasenko
Python and pymongo
蟒蛇和 pymongo
Finding objects between two dates in Python with pymongo
in collection posts
(based on the tutorial):
在 Python 中使用pymongo
集合查找两个日期之间的对象posts
(基于教程):
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)
Where {"$gte": from_date, "$lt": to_date}
specifies the range in terms of datetime.datetime
types.
where{"$gte": from_date, "$lt": to_date}
指定范围的datetime.datetime
类型。
回答by GSK
db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();
Replace collection
with name of collection you want to execute query
替换collection
为要执行查询的集合名称
回答by Sunil Pal
Use this code to find the record between two dates using $gte
and $lt
:
使用此代码使用$gte
和查找两个日期之间的记录$lt
:
db.CollectionName.find({"whenCreated": {
'$gte': ISODate("2018-03-06T13:10:40.294Z"),
'$lt': ISODate("2018-05-06T13:10:40.294Z")
}});
回答by Tính Ng? Quang
Using with Moment.jsand 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) { ... });
回答by Kevin007
You can also check this out. If you are using this method, then use the parse function to get values from Mongo Database:
你也可以看看这个。如果您使用此方法,则使用 parse 函数从 Mongo 数据库中获取值:
db.getCollection('user').find({
createdOn: {
$gt: ISODate("2020-01-01T00:00:00.000Z"),
$lt: ISODate("2020-03-01T00:00:00.000Z")
}
})
回答by KARTHIKEYAN.A
use $gteand $lteto find between date data's in mongodb
使用$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")}})
回答by ZacharyST
Why not convert the string to an integer of the form YYYYMMDDHHMMSS? Each increment of time would then create a larger integer, and you can filter on the integers instead of worrying about converting to ISO time.
为什么不将字符串转换为 YYYYMMDDHHMMSS 形式的整数?每个时间增量都会创建一个更大的整数,您可以对整数进行过滤,而不必担心转换为 ISO 时间。