如何正确增加mongoDB中的许多日期? [英] How does one properly increment many dates in mongoDB?
问题描述
不是一个特别强大的Javascript人,我在使用Mongo更新大量 Date
对象时遇到了一些麻烦。
Not being a particularly strong Javascript guy, I'm having a bit of trouble trying to update a lot of Date
objects in Mongo.
似乎 $ inc $ c尚未为
实施$ c>。所以,为了尝试将一堆日期推迟一天,我通过日期
对象 mongo myScript.js
:
It seems that $inc
has not yet been implemented for Date
objects. So, to try and bump a bunch of dates by a day, I called (something like) this script from bash via mongo myScript.js
:
conn = new Mongo();
db = conn.getDB('myDatabase');
var incrementDates = function() {
db.blah.find(myQuery).forEach(function(doc) {
db.blah.update(
{ _id : doc._id
, my_date : { $exists : true }
}
, { $set : { my_date : new Date(doc.my_date.getTime() + 86400000) }}
);
});
}
incrementDates();
mongoDB shell中的基本思想似乎运行良好:
The basic idea seems to work well enough in the mongoDB shell:
> var doc = db.blah.findOne(myQuery)
> doc.my_date
ISODate("1962-11-02T23:00:00Z")
> new Date(doc.my_date.getTime() + 86400000);
ISODate("1962-11-03T23:00:00Z")
但不是这样好在脚本中:
But not so well in the script:
TypeError: doc.my_date has no properties
所以我认为我试图在 null上调用
某处,即使我的更新中的查询只返回 getTime
my_date
存在的文档。
So I take it that I'm trying to call getTime
on a null
somewhere, even though the query in my update should only return documents where my_date
exists.
关于这里发生了什么的任何想法?更重要的是:有更好的方法吗?
Any ideas as to what's happening here? More importantly: is there a better way to do this?
推荐答案
问题是我的 $存在
查询(显然,第二次看)在错误的地方。正在退回的文件肯定不包括 my_date
。
The problem is that my $exists
query is (obviously, on second look) in the wrong place. Documents were being returned that, surely enough, didn't include my_date
.
这是补丁功能,按预期工作。
Here's the patched up function, which works as expected.
var incrementDates = function() {
db.blah.find({ ... , my_date : { $exists : true } ).forEach(function(doc) {
db.blah.update(
{ _id : doc._id }
, { $set : { my_date : new Date(doc.my_date.getTime() + 86400000) }}
);
});
}
这篇关于如何正确增加mongoDB中的许多日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!