Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert an array item after a specific value in mongodb

I have db like;

{"_id" : 1 , children: ["2", "123", "5"]}

I want to insert an element into children array. It is easy when you know the index. $position can be used for this purpose. Like;

db.module_menu.update({"_id" : "1"} , 
                      {$push : {"children" : { 
                                  $each : ["12"] , $position : 1}}});

But lets say I don't know the position index, I know the value of element that I want to insert after.

I have value: 12 and value that I want to insert after. insertAfter: 2

As a result it should be;

{"_id" : 1, text: "" , children: ["2","12", "123", "5"]}

How can I do it?

Go through each element in the children array find the index of value and by using $position, insert the value. Is it the only way to do it?

like image 507
Yigit Can Avatar asked Nov 08 '22 19:11

Yigit Can


1 Answers

I'm afraid it's not possible. There's an ancient issue to use $function in update but you're only way is to read, modify and persist the array.

On the other hand if you an array of embedded documents then you can use the $ positional operator. The $ can be used to $set a value in you simple array but to $push.

> db.test.find()
{ "_id" : ObjectId("56d9570d09e01f20e254d0f3"), "a" : [ 1, 2, 3 ] }
> db.test.update({"_id": ObjectId("56d9570d09e01f20e254d0f3"), "a": 2},
                 {$push: {a: {$each: [2], $position: "$"}}})
WriteResult({
    "nMatched" : 0,
    "nUpserted" : 0,
    "nModified" : 0,
    "writeError" : {
        "code" : 2,
        "errmsg" : "The value for $position must be a positive numeric value not a String"
    }
})
like image 191
Thomas R. Koll Avatar answered Nov 15 '22 07:11

Thomas R. Koll