在mongoDb中,如何通过其索引删除数组元素? [英] In mongoDb, how do you remove an array element by its index?

查看:389
本文介绍了在mongoDb中,如何通过其索引删除数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例中,假定文档位于 db.people 集合中.

In the following example, assume the document is in the db.people collection.

如何通过 index 删除兴趣数组的第三个元素?

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:

这篇关于在mongoDb中,如何通过其索引删除数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆