Home > Enterprise >  Update last element of a nested array in mongodb
Update last element of a nested array in mongodb

Time:12-22

I have tried the below query of mongoose which does not seem to work:

Model.findOneAndUpdate(
    {
        name: origin
    },
    {
        $set: {
            'field1.$[id1].field2.-1': "value"
        }
    },
    {
        arrayFilters: [
            { 'id1.userId': "customerId" }
        ],
        new: true
    }
);

Note: field1 and field2 are arrays

The negative indexes are not accepted by MongoDB which is causing problems.

CodePudding user response:

You may consider using the $set (aggregation) operator and use double $map operator:

db.collection.aggregate([
    { $match: { name: "myname" } }
    {
        $set: {
            field1: {
                $map: {
                    input: "$field1",
                    in: {
                        $cond: {
                            if: { $ne: [ "$$this.userId", "customerId" ] },
                            then: "$$this",
                            else: {
                                $mergeObjects: [
                                    "$$this",
                                    { 
                                        field2: { 
                                            $concatArrays: [
                                                { $slice: [ "$$this.field2", { $add: [ { $size: "$$this.field2" }, -1 ] } ] },
                                                ["value"]
                                            ]
                                        } 
                                    }
                                ]
                            }
                        }
                    }
                }
            }
        }
    }
])

Mongo Playground

CodePudding user response:

Apply the $set operator together with the $ positional operator in your update to change the name field.

The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array, thus your final update statement should look like:

db.collection.update(
    { "friends.u.username": "michael" }, 
    { "$set": { "friends.$.u.name": "hello" } }
)

Answer taken from - https://stackoverflow.com/a/34431571

  • Related