如何将值添加到MongoDB中一个阵列的顶部? [英] how do i add a value to the top of an array in mongodb?
问题描述
我怎么值添加到MongoDB中一个数组的顶部?
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?
当我做的:
{$push:{colors:"yellow"}}
我会得到这样的:
i'd get this:
{ "colors" : [ "red", "green", "blue", "yellow" ] }
我想这样的:
{ "colors" : [ "yellow", "red", "green", "blue"] }
在此先感谢!
推荐答案
在一个阵列前端的unshift插入数据..而推插入它的结束。
例如在JavaScript中:
"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" ]
但不幸的是这不是由蒙戈API作为一个原子操作的支持:
But unfortunately this isn't supported by the Mongo API as an atomic operation:
http://www.mongodb.org/display/DOCS/Updating
它只是支持推
你有多大的阵列?
您可以醚假设你在蒙戈阵列总是存储在倒车时,和使用推,或者你可以读出的数组,不印字修改它,然后再存放起来(这不会是原子虽然)
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)
这篇关于如何将值添加到MongoDB中一个阵列的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!