How to delete n-th element of array in mongodb

2019-01-14 12:14发布

问题:

For example i have a document

db.test.save({_id: 1, list:[
    {key: "a"},
    {key: "b"},
    {key: "c"},
    {key: "d"},
    {key: "e"}
]})

and i need remove second element from the list. For now I do that in a two steps. First of all I unset second list element but unset operator do not remove element, it is going to be null, after that I pull any nullable value from the list field

db.test.update({_id: 1}, {$unset: {"list.2": 1}})
db.test.update({_id: 1}, {$pull: {list: null}})

I want to ask whether there is solution do that in a one operation?

回答1:

No, unfortunately what you are doing is currently the best option. Have a look at this question: In mongoDb, how do you remove an array element by its index which links to a Jira for this very issue.



回答2:

if you know the value which you want to remove

db.test.update({{_id: 1},{"$pull" : {"list" : { "key" : "c"}}},false,false)

more info at

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray



回答3:

Not at the current time. As it was answered in There is no straight way of pulling/removing by array index.

There is an open issue asking for that operation, even though this workaround is ok, notwithstanding it is not an atomic solution.



标签: mongodb