以下文件:
{
"_id": ObjectId("5d648b0d5aeada5177bb54e4"),
"time": [{
"start": "2019/8/25 9:59:30",
"end": "2019/8/25 10:59:30"
},
{
"start": "2019/8/26 9:59:30",
"end": "2019/8/26 10:59:30"
},
{
"start": "2019/8/27 9:59:30",
"end": "2019/8/26 9:59:30"
}
]
}
如何更新数组中的最后一个元素?
我已经尝试过:
db.document.update(
{
"_id": ObjectId("5d648b0d5aeada5177bb54e4")
},
{
$set: {
"time.-1.end": "2019/8/26 10:59:30"
}
}
)
但是它不起作用...
答案 0 :(得分:0)
这很简单。获取最后一个元素的索引/位置。
var data = {
"_id" : "5d648b0d5aeada5177bb54e4",
"time" : [
{
"start" : "2019/8/25 9:59:30",
"end" : "2019/8/25 10:59:30"
},
{
"start" : "2019/8/26 9:59:30",
"end" : "2019/8/26 10:59:30"
},
{
"start" : "2019/8/27 9:59:30",
"end" : "2019/8/26 9:59:30"
}
]
}
var len = data.time.length - 1;
var objUpdate = {};
var updateQuery = "time." + len + ".end";
objUpdate[updateQuery] = "2019/8/26 11:59:30";
db.getCollection('test').update({"_id" : ObjectId("5d648b0d5aeada5177bb54e4")}, {$set:objUpdate});
答案 1 :(得分:0)
使用time.start字段过滤出文档:
请尝试以下查询:
db.arraytest.updateOne({"_id" : ObjectId("5d648b0d5aeada5177bb54e4"), "time.start" : "2019/8/27 9:59:30"},
{$set: { "time.$.end": "2019/8/26 10:59:30" }})