Is it possible to insert an element in the middle of an array in a MongoDB document?

Let's say I have a document in a Mongo database that looks like this:

{ pages: [ { elements: [ {id:1}, {id:2}, {id:3} ] }, { elements: [ ... ] } ] } 

and that the order of elements within a page has semantic meaning (e.g., stacking). Now say that I want to add a new element before the second element on the first page. The desired state of the resulting document is as follows:

 { pages: [ { elements: [ {id:1}, {id:4}, // <------ element inserted here {id:2}, {id:3} ] }, { elements: [ ... ] } ] } 

In Mongo docs, I see how to add elements to the end of an array and how to update the value of an existing element, but not how to insert in the middle of an array (à la PHP array_splice ). Is this possible only by reassigning the entire array to a new array with the desired element inserted in the middle?

+4
source share
3 answers

Essentially, if you use update , the order is not guaranteed. To add to the problems you are trying to do, while you can update an item with a specific position , you cannot call $addToSet or $push with a similar specification.

The corresponding function request for what you want:

https://jira.mongodb.org/browse/SERVER-2363

So far, as you suspected, you cannot do this without pulling out the array, manipulating it as you like, and using $set .

+1
source

MongoDB now supports this feature. You can insert an element in the middle of the array using the $ position operator.

Luck

+1
source

Shouldn't the layer number be stored as an attribute of an array element? The BSON specification says that arrays are key-value pairs, so you need to use your layer number as the key in the array. (MongoDB uses BSON to store data)

0
source

All Articles