如何在 mongodb 的数组顶部添加一个值?

how do i add a value to the top of an array in mongodb?(如何在 mongodb 的数组顶部添加一个值?)
本文介绍了如何在 mongodb 的数组顶部添加一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何在 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 的数组顶部添加一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)