如何在 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模板网!
检查一个多边形点是否在传单中的另一个内部Check if a polygon point is inside another in leaflet(检查一个多边形点是否在传单中的另一个内部)
更改传单标记群集图标颜色,继承其余默认 CSSChanging leaflet markercluster icon color, inheriting the rest of the default CSS properties(更改传单标记群集图标颜色,继承其余默认
触发点击传单标记Trigger click on leaflet marker(触发点击传单标记)
如何更改 LeafletJS 中的默认加载磁贴颜色?How can I change the default loading tile color in LeafletJS?(如何更改 LeafletJS 中的默认加载磁贴颜色?)
将 Leaflet 图层控件添加到侧边栏Adding Leaflet layer control to sidebar(将 Leaflet 图层控件添加到侧边栏)
Leaflet - 在弹出窗口中获取标记的纬度和经度Leaflet - get latitude and longitude of a marker inside a pop-up(Leaflet - 在弹出窗口中获取标记的纬度和经度)