我一直在玩在 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 之间的所有对象?我是否需要更新我的文档,以便以特定格式存储日期?
2010-04-29T00:00:00.000Z
比以毫秒为单位计算相同的日期/时间要容易得多。您还可以很容易地进行时区转换。此外,Dates 已经处理了诸如闰日、闰秒以及您通常不想自己处理的其他奇怪事件。
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)" }
根据我的实验,您需要将日期序列化为 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" }
在第二个示例中,没有预期的结果,但仍然有一个结果。这是因为完成了基本的字符串比较。
澄清。重要的是要知道:
是的,您必须传递一个 Javascript Date 对象。
是的,它必须是 ISODate 友好的
是的,根据我的经验,您需要将日期操作为 ISO
是的,处理日期通常总是一个乏味的过程,mongo 也不例外
这是一个工作代码片段,我们在其中进行了一些日期操作以确保 Mongo(这里我使用的是 mongoose 模块并希望日期属性小于(之前)作为 myDate 参数给出的日期的行的结果)可以处理它正确:
var inputDate = new Date(myDate.toISOString());
MyModel.find({
'date': { $lte: inputDate }
})
Python 和 pymongo
在 Python 中使用集合 posts
中的 pymongo
查找两个日期之间的对象(基于 tutorial):
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)
其中 {"$gte": from_date, "$lt": to_date}
根据 datetime.datetime
类型指定范围。
MongoDB 实际上将日期的毫秒存储为 int(64),如 http://bsonspec.org/#/specification 所述
但是,当您检索日期时,它会变得相当混乱,因为客户端驱动程序将使用自己的本地时区实例化一个日期对象。 mongo 控制台中的 JavaScript 驱动程序肯定会这样做。
所以,如果你关心你的时区,那么确保你知道当你把它拿回来时它应该是什么。这对于查询来说应该没那么重要,因为它仍然等同于相同的 int(64),无论您的日期对象在哪个时区(我希望如此)。但我肯定会使用实际的日期对象(而不是字符串)进行查询,并让驱动程序做它的事情。
db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();
将 collection
替换为您要执行查询的集合名称
使用此代码通过 $gte
和 $lt
查找两个日期之间的记录:
db.CollectionName.find({"whenCreated": {
'$gte': ISODate("2018-03-06T13:10:40.294Z"),
'$lt': ISODate("2018-05-06T13:10:40.294Z")
}});
与 Moment.js 和 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) { ... });
你也可以看看这个。如果您使用此方法,则使用 parse 函数从 Mongo 数据库中获取值:
db.getCollection('user').find({
createdOn: {
$gt: ISODate("2020-01-01T00:00:00.000Z"),
$lt: ISODate("2020-03-01T00:00:00.000Z")
}
})
db.collection.find({$and:
[
{date_time:{$gt:ISODate("2020-06-01T00:00:00.000Z")}},
{date_time:{$lt:ISODate("2020-06-30T00:00:00.000Z")}}
]
})
##In case you are making the query directly from your application ##
db.collection.find({$and:
[
{date_time:{$gt:"2020-06-01T00:00:00.000Z"}},
{date_time:{$lt:"2020-06-30T00: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 时间。
将您的日期转换为 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`) ]
},
]
}
}
}
}
}
])
对于那些使用 Integromat 和 MongoDB 的人:我一直在努力寻找正确的方法来查询两个日期之间的所有记录。最后,我所要做的就是按照这里的一些解决方案中的建议删除 ISODate
。所以完整的代码是:
"created": {
"$gte": "2016-01-01T00:00:00.000Z",
"$lt": "2017-01-01T00:00:00.000Z"
}
这article帮助我实现了我的目标。
以 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")
}
})
Scala:使用 joda DateTime 和 BSON 语法(reactivemongo):
val queryDateRangeForOneField = (start: DateTime, end: DateTime) =>
BSONDocument(
"created_at" -> BSONDocument(
"$gte" -> BSONDateTime(start.millisOfDay().withMinimumValue().getMillis),
"$lte" -> BSONDateTime(end.millisOfDay().withMaximumValue().getMillis)),
)
其中“2021-09-08T06:42:51.697Z”的 millisOfDay().withMinimumValue()
将为“2021-09-08T00:00:00.000Z”,“2021-09-08T06:42:51.697Z”的 millisOfDay(). withMaximumValue()
将为是“2021-09-08T23:59:99.999Z”
我根据我的要求尝试了这个模型我需要在以后创建对象时存储一个日期我想在我的 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}})