简体   繁体   English

是否可以在MongoDB文档的数组中间插入元素?

[英]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: 假设我在mongo DB中有一个文档,看起来像这样:

{
    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 ). Mongo文档中,我看到了如何在数组的末尾添加元素以及如何更新现有元素的值,但是没有看到如何插入数组的中间(如PHP的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. 本质上,如果您使用update ,则不能保证顺序。 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. 要添加尝试尝试建议的问题,尽管可以在特定位置更新元素,但是不能使用类似的规范调用$addToSet$push

The relevant feature request for what you want is here: 您想要的相关功能请求在这里:

https://jira.mongodb.org/browse/SERVER-2363 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 . 但是,就目前而言,正如您所怀疑的那样,如果不拉出数组,根据需要进行操作并使用$set ,就无法做到这一点。

MongoDB now supports this feature. MongoDB现在支持此功能。 You can insert an element to the middle of an array using the $position operator. 您可以使用$ position运算符将元素插入数组的中间。

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) BSON规范说数组是键-值对,因此您需要使用层号作为数组中的键。(MongoDB使用BSON来存储数据)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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