node.js MongoDB/Mongoose 在特定日期查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11973304/
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
MongoDB/Mongoose querying at a specific date?
提问by Unitech
Is it possible to query for a specific date ?
是否可以查询特定日期?
I found in the mongo Cookbook that we can do it for a range Querying for a Date RangeLike that :
我在 mongo Cookbook 中发现,我们可以为范围查询日期范围,如下所示:
db.posts.find({"created_on": {"$gte": start, "$lt": end}})
But is it possible for a specific date ? This doesn't work :
但是有可能是特定日期吗?这不起作用:
db.posts.find({"created_on": new Date(2012, 7, 14) })
回答by rdrey
That should work if the dates you saved in the DB are without time (just year, month, day).
如果您保存在数据库中的日期没有时间(只有年、月、日),那应该可行。
Chances are that the dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day.
您保存的日期可能是new Date(),其中包括时间组件。要查询这些时间,您需要创建一个包含一天中所有时刻的日期范围。
db.posts.find( //query today up to tonight
{"created_on": {"$gte": new Date(2012, 7, 14), "$lt": new Date(2012, 7, 15)}})
回答by Pier-Luc Gendreau
...5+ years later, I strongly suggest using date-fnsinstead
... 5年以上后,我强烈建议使用日期FNS代替
import endOfDayfrom 'date-fns/endOfDay'
import startOfDay from 'date-fns/startOfDay'
MyModel.find({
createdAt: {
$gte: startOfDay(new Date()),
$lte: endOfDay(new Date())
}
})
For those of us using Moment.js
对于我们这些使用Moment.js 的人
const moment = require('moment')
const today = moment().startOf('day')
MyModel.find({
createdAt: {
$gte: today.toDate(),
$lte: moment(today).endOf('day').toDate()
}
})
Important: all moments are mutable!
重要提示:所有时刻都是可变的!
tomorrow = today.add(1, 'days')does not work since it also mutates today. Calling moment(today)solves that problem by implicitly cloning today.
tomorrow = today.add(1, 'days')不起作用,因为它也会变异today。调用moment(today)通过隐式克隆解决了这个问题 today。
回答by Faisal Hasnain
Yeah, Date object complects date and time, so comparing it with just date value does not work.
是的,Date 对象包含日期和时间,因此仅将其与日期值进行比较是行不通的。
You can simply use the $whereoperator to express more complex condition with Javascript boolean expression :)
您可以简单地使用$where运算符来表达更复杂的条件与 Javascript 布尔表达式 :)
db.posts.find({ '$where': 'this.created_on.toJSON().slice(0, 10) == "2012-07-14"' })
created_onis the datetime field and 2012-07-14is the specified date.
created_on是日期时间字段并且2012-07-14是指定的日期。
Date should be exactly in YYYY-MM-DDformat.
日期应完全采用YYYY-MM-DD格式。
Note:Use $wheresparingly, it has performance implications.
注意:请$where谨慎使用,它会影响性能。
回答by Michael D Johnson
Have you tried:
你有没有尝试过:
db.posts.find({"created_on": {"$gte": new Date(2012, 7, 14), "$lt": new Date(2012, 7, 15)}})
The problem you're going to run into is that dates are stored as timestamps in Mongo. So, to match a date you're asking it to match a timestamp. In your case I think you're trying to match a day (ie. from 00:00 to 23:59 on a specific date). If your dates are stored without times then you should be okay. Otherwise, try specifying your date as a range of time on the same day (ie. start=00:00, end=23:59) if gte doesn't work.
您将遇到的问题是日期在 Mongo 中存储为时间戳。因此,要匹配日期,您要求它匹配时间戳。在您的情况下,我认为您正在尝试匹配一天(即从特定日期的 00:00 到 23:59)。如果您的日期没有时间存储,那么您应该没问题。否则,如果 gte 不起作用,请尝试将日期指定为同一天的时间范围(即开始=00:00,结束=23:59)。
回答by Daniel Kmak
You can use following approach for API method to get results from specific day:
您可以使用以下 API 方法来获取特定日期的结果:
# [HTTP GET]
getMeals: (req, res) ->
options = {}
# eg. api/v1/meals?date=Tue+Jan+13+2015+00%3A00%3A00+GMT%2B0100+(CET)
if req.query.date?
date = new Date req.query.date
date.setHours 0, 0, 0, 0
endDate = new Date date
endDate.setHours 23, 59, 59, 59
options.date =
$lt: endDate
$gte: date
Meal.find options, (err, meals) ->
if err or not meals
handleError err, meals, res
else
res.json createJSON meals, null, 'meals'
回答by Brett
We had an issue relating to duplicated data in our database, with a date field having multiple values where we were meant to have 1. I thought I'd add the way we resolved the issue for reference.
我们遇到了与数据库中重复数据相关的问题,日期字段具有多个值,而我们本应为 1。我想我会添加解决问题的方式以供参考。
We have a collection called "data" with a numeric "value" field and a date "date" field. We had a process which we thought was idempotent, but ended up adding 2 x values per day on second run:
我们有一个名为“data”的集合,带有一个数字“value”字段和一个日期“date”字段。我们有一个我们认为是幂等的过程,但最终在第二次运行时每天添加 2 个值:
{ "_id" : "1", "type":"x", "value":1.23, date : ISODate("2013-05-21T08:00:00Z")}
{ "_id" : "2", "type":"x", "value":1.23, date : ISODate("2013-05-21T17:00:00Z")}
We only need 1 of the 2 records, so had to resort the javascript to clean up the db. Our initial approach was going to be to iterate through the results and remove any field with a time of between 6am and 11am (all duplicates were in the morning), but during implementation, made a change. Here's the script used to fix it:
我们只需要 2 条记录中的 1 条,因此不得不使用 javascript 来清理数据库。我们最初的方法是遍历结果并删除早上 6 点到 11 点之间的任何字段(所有重复都在早上),但在实施过程中进行了更改。这是用于修复它的脚本:
var data = db.data.find({"type" : "x"})
var found = [];
while (data.hasNext()){
var datum = data.next();
var rdate = datum.date;
// instead of the next set of conditions, we could have just used rdate.getHour() and checked if it was in the morning, but this approach was slightly better...
if (typeof found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] !== "undefined") {
if (datum.value != found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()]) {
print("DISCREPENCY!!!: " + datum._id + " for date " + datum.date);
}
else {
print("Removing " + datum._id);
db.data.remove({ "_id": datum._id});
}
}
else {
found[rdate.getDate()+"-"+rdate.getMonth() + "-" + rdate.getFullYear()] = datum.value;
}
}
and then ran it with mongo thedatabase fixer_script.js
然后运行它 mongo thedatabase fixer_script.js

