Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb update the last array element

Tags:

mongodb

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...

like image 358
glowwormX Avatar asked Aug 27 '19 06:08

glowwormX


People also ask

How do you update an element in an array in MongoDB?

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.

How do I get the last element in MongoDB?

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).

How do I update a nested array in MongoDB?

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.


2 Answers

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});
like image 161
Harish Mahajan Avatar answered Oct 03 '22 18:10

Harish Mahajan


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" }})
like image 22
Dexter Avatar answered Oct 03 '22 18:10

Dexter