MongoDB更新:根据现有字段生成新字段,或就地更新 [英] MongoDB update: Generate new field based on existing field, or update in place
问题描述
我已经搞混了一段时间,没有找到有关如何完成此任务的示例或说明.
I have been messing around with this for a while now and have found no examples nor explanations about how to accomplish this task.
我有一个文档集合,每个文档都有一个日期/时间字段.理想情况下,我需要为每个文档生成一个新字段,其中值基于来自日期/时间字段的时间,并添加了一个常数因子.
I have a collection of documents, each document has a date/time field. Ideally I need to generate a new field for each document where the value is based on the time from the date/time field with a constant factor added.
或者,仅更新适当的值就足够了.
Alternatively, simply updating the value in place would suffice.
我无法弄清楚如何在mongo shell更新语句中引用当前文档.
I have not been able to figure out how to reference the current document in a mongo shell update statement.
这是愚蠢的吗?我应该放弃并编写应用程序来完成看似简单的操作吗?
Is this folly? Should I give up and write an application do to complete this seemingly simple operation?
谢谢!
推荐答案
有时候,简单地写出问题即可带您解决. Kinda hacky,肯定很奇怪,但是似乎可以工作:
Sometimes simply writing the question out brings you to a solution. Kinda hacky, and definitely weird, but seems to work:
db.actuals.find().forEach(
function(d) {
var dt = d.date;
var ndt = new Date(d.date).setHours(dt.getHours() - 8);
db.actuals.update( {_id: d._id}, { $set: { local: new Date(ndt) } } );
}
)
这篇关于MongoDB更新:根据现有字段生成新字段,或就地更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!