{
"_id" : ObjectId("57693a852956d5301b348a99"),
"First_Name" : "Sri Ram",
"Last_Name" : "Bandi",
"Email" : "chinni001sriram@gmail.com",
"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数据。我想将duration
设置为登录和注销时间的差异。所以,我执行了以下查询:
db.sessionData.update(
{ "Sessions.ID": "1778142655749042"},
{ $set: {
"Sessions.$.Duration": ISODate("Sessions.$.Logout_Time" - "Sessions.$.Login_Time")
}
}
)
但我得到的结果是:
{
"_id" : ObjectId("57693a852956d5301b348a99"),
"First_Name" : "Sri Ram",
"Last_Name" : "Bandi",
"Email" : "chinni001sriram@gmail.com",
"Sessions" : [
{
"Class" : "facebook",
"ID" : "1778142655749042",
"Login_Time" : ISODate("2016-06-21T13:00:53.867Z"),
"Logout_Time" : ISODate("2016-06-21T13:01:04.640Z"),
"Duration" : ISODate("2016-06-21T13:02:58.010Z")
}
],
"Count" : 1
}
和持续时间设置为当前时间/日期而不是差异。
答案 0 :(得分:1)
您可以使用聚合框架使用 $divide
和 $subtract
运算符执行算术运算,以便在秒。公式由
Duration (sec) = (Logout_Time - Login_Time)/1000
聚合管道应该为您提供具有此计算值的新字段,然后您可以在 forEach()
aggregate()
光标方法>结果迭代结果中的文档并更新集合。
以下示例显示了这一点:
db.sessionData.aggregate([
{ "$match": { "Sessions.ID" : "1778142655749042" } },
{ "$unwind": "$Sessions" },
{ "$match": { "Sessions.ID" : "1778142655749042" } },
{
"$project": {
"Duration": {
"$divide": [
{ "$subtract": [ "$Sessions.Logout_Time", "$Sessions.Login_Time" ] },
1000
]
}
}
}
]).forEach(function (doc) {
db.sessionData.update(
{ "Sessions.ID": "1778142655749042", "_id": doc._id },
{
"$set": { "Sessions.$.Duration": doc.Duration }
}
);
});
查询结果
{
"_id" : ObjectId("57693a852956d5301b348a99"),
"First_Name" : "Sri Ram",
"Last_Name" : "Bandi",
"Email" : "chinni001sriram@gmail.com",
"Sessions" : [
{
"Class" : "facebook",
"ID" : "1778142655749042",
"Login_Time" : ISODate("2016-06-21T13:00:53.867Z"),
"Logout_Time" : ISODate("2016-06-21T13:01:04.640Z"),
"Duration" : 10.773
}
],
"Count" : 1
}