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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)