問題描述
如何在 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 的數組頂部添加一個值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!