how do i add a value to the top of an array in mongodb?

有些话、适合烂在心里 提交于 2019-12-17 16:37:21

问题


how do i add a value to the top of an array in mongodb?

say i have this document in my mongo collection:

{ "colors" : [ "red", "green", "blue" ] }

how do i add "yellow" to the front of the list?

when i do:

{$push:{colors:"yellow"}}

i'd get this:

{ "colors" : [ "red", "green", "blue", "yellow" ] }

i want this:

{ "colors" : [ "yellow", "red", "green", "blue"] }

thanks in advance!


回答1:


"unshift" inserts data in the front of an array.. whereas "push" inserts it at the end. e.g. in JavaScript:

> a = ['red','green','blue']
[ "red", "green", "blue" ]
> a.unshift("yellow")
4
> a
[ "yellow", "red", "green", "blue" ]

But unfortunately this isn't supported by the Mongo API as an atomic operation:

http://www.mongodb.org/display/DOCS/Updating

it just supports "push"


How big is your array?

you could ether assume that your array in Mongo is always stored in reverse, and use push, or you could read-out the array, modify it with unshift, and then store it again (which wouldn't be atomic though)




回答2:


For anybody new to this, MongoDB 2.6+ supports the $position operator, which can be used to achieve the desired effect. The benefit here being that you don't need to return your entire document array, update it locally and save it - the $position operator means things can be done atomically.

You need to use it in conjunction with $each:

$push: { colors: { $each: ['yellow'], $position: 0 } }


来源:https://stackoverflow.com/questions/7936019/how-do-i-add-a-value-to-the-top-of-an-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!