问题描述
如何在 mongodb 的数组顶部添加一个值?
how do i add a value to the top of an array in mongodb?
假设我的 mongo 收藏中有此文档:
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"}}
我会得到这个:
{ "colors" : [ "red", "green", "blue", "yellow" ] }
我想要这个:
{ "colors" : [ "yellow", "red", "green", "blue"] }
提前致谢!
推荐答案
"unshift" 在数组的前面插入数据.. 而"push" 在末尾插入数据.例如在 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" ]
但不幸的是,Mongo API 不支持将其作为原子操作:
But unfortunately this isn't supported by the Mongo API as an atomic operation:
http://www.mongodb.org/display/DOCS/Updating
它只支持推送"
您的阵列有多大?
你可以假设你在 Mongo 中的数组总是反向存储,并使用 push,或者你可以读出数组,用 unshift 修改它,然后再次存储它(虽然这不是原子的)
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 的数组顶部添加一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!