the following documents:
{
"_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"
}
]
}
How to update the last element in array?
I'm already tried:
db.document.update(
{
"_id": ObjectId("5d648b0d5aeada5177bb54e4")
},
{
$set: {
"time.-1.end": "2019/8/26 10:59:30"
}
}
)
but it does not work...
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.
To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).
Update Nested Arrays in Conjunction with $[] The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.
it is very simple. get the last element's index/position.
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});
Filter out the document using time.start
field:
Try the below query:
db.arraytest.updateOne({"_id" : ObjectId("5d648b0d5aeada5177bb54e4"), "time.start" : "2019/8/27 9:59:30"},
{$set: { "time.$.end": "2019/8/26 10:59:30" }})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With