本文介绍了引用文档属性以在 mongo 更新查询中更新另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
{
"_id" : ObjectId("57693a852956d5301b348a99"),
"First_Name" : "Sri Ram",
"Last_Name" : "Bandi",
"Email" : "[email protected]",
"Sessions" : [
{
"Class" : "facebook",
"ID" : "1778142655749042",
"Login_Time" : ISODate("2016-06-21T13:00:53.867Z"),
"Logout_Time" : ISODate("2016-06-21T13:01:04.640Z"),
"Duration" : null
}
],
"Count" : 1
}
这是我的mongo数据,我想将注销时间设置为当前时间,将持续时间"设置为同时登录和注销时间的差值.所以我执行了以下查询:
This is my mongo data and I want to set the logout time as current time and "duration" as the difference of login and logout time simultaneously. So I executed the following query:
collection.update(
{
"Sessions.ID": 1778142655749042,
"Sessions.Logout_Time": null
},
{
"$set": {
"Sessions.$.Logout_Time": new Date(),
"Sessions.$.Duration": new Date(new Date() - "$Sessions.$.Login_Time"),
},
}
);
但我得到的结果是将注销时间设置为当前时间,但持续时间设置为NaN".
But the result I'm getting is setting logout time as current time but duration is set to 'NaN'.
推荐答案
Mongo 不支持在更新中引用当前对象
所以你可以做的是:
db.collection.find( { "Sessions.ID": 1778142655749042, "Sessions.Logout_Time": null
}).forEach(function(doc){
for(var session in doc.Sessions){
if(!session.Logout_Time){
session.Logout_Time = new Date();
session.Duration = new Date(new Date() - doc.Login_Time");
}
}
db.collection.save(doc);
});
这篇关于引用文档属性以在 mongo 更新查询中更新另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!