5

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?

4
  • You can try with $addToSet Commented Mar 4, 2016 at 9:30
  • $addToSet might not keep the arrays order Commented Mar 4, 2016 at 9:32
  • $addToSet is just like $push? It adds to the end of the set. Am I wrong? Commented Mar 4, 2016 at 9:38
  • no, they are different in this vital point: $addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set. Commented Mar 4, 2016 at 9:48

2 Answers 2

1

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"
    }
})
Sign up to request clarification or add additional context in comments.

1 Comment

The example you give doesn't work. You've even included the resulting error in the output - namely that "$" resolves to a string but the position must be an integer.
0

There is no function to get position and update at one go, so in you problem you need to get position before update and pass it to query - so that means we are operating on 1:1 bassis.

Other approach is to retrieve data - perform in-place update and push full array set back to mongo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.