Insert an array item after a specific value in mongodb

Viewed 800

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?

2 Answers
Related