简体   繁体   中英

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

Say I have a document in a mongo DB 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 (eg, stacking). Now say that I want to add a new element before the second element in the first page. The desired state of the resulting document is this:

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

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

Essentially, if you use update , order is not guaranteed. To add to the issues attempting what you suggest, while you can update an element at a specific position , you can't call $addToSet or $push with a similar specification.

The relevant feature request for what you want is here:

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

For now though, as you suspected, you can't do it without pulling out the array, manipulating it as you desire and the using $set .

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

Good Luck

Shouldn't you just be storing the layer number as an attribute of the array element? BSON specification says 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM