在 mongoDb 中,如何通过索引删除数组元素? [英] In mongoDb, how do you remove an array element by its index?
问题描述
在以下示例中,假设文档位于 db.people 集合中.
In the following example, assume the document is in the db.people collection.
如何通过index删除interests数组的第三个元素?
How to remove the 3rd element of the interests array by it's index?
{
"_id" : ObjectId("4d1cb5de451600000000497a"),
"name" : "dannie",
"interests" : [
"guitar",
"programming",
"gadgets",
"reading"
]
}
这是我目前的解决方案:
This is my current solution:
var interests = db.people.findOne({"name":"dannie"}).interests;
interests.splice(2,1)
db.people.update({"name":"dannie"}, {"$set" : {"interests" : interests}});
有没有更直接的方法?
推荐答案
没有直接通过数组索引拉/移除的方法.事实上,这是一个开放问题 http://jira.mongodb.org/browse/SERVER-1014 ,你可以投票给它.
There is no straight way of pulling/removing by array index. In fact, this is an open issue http://jira.mongodb.org/browse/SERVER-1014 , you may vote for it.
解决方法是先使用 $unset,然后使用 $pull:
The workaround is using $unset and then $pull:
db.lists.update({}, {$unset : {"interests.3" : 1 }})
db.lists.update({}, {$pull : {"interests" : null}})
更新:正如一些评论中提到的,这种方法不是原子的,如果其他客户端在两个操作之间读取和/或写入,可能会导致一些竞争条件.如果我们需要操作是原子的,我们可以:
Update: as mentioned in some of the comments this approach is not atomic and can cause some race conditions if other clients read and/or write between the two operations. If we need the operation to be atomic, we could:
- 从数据库中读取文档
- 更新文档并移除数组中的项目
- 替换数据库中的文档.为了确保文档在我们阅读后没有改变,我们可以使用更新如果当前模式描述 在 mongo 文档中
这篇关于在 mongoDb 中,如何通过索引删除数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!