你可以让 mongo $push prepend 而不是 append 吗? [英] Can you have mongo $push prepend instead of append?
问题描述
当我执行 mongo $push 时,我希望在我的集合的开头添加 push add,而不是附加到末尾.
I'd like to have push add at the beginning of my set rather than appended to the end when I do a mongo $push.
是否可以进行原子推送更新,将元素添加为第一个而不是最后一个?
Is it possible to do an atomic push update that adds elements as the first rather than the last?
2014 年更新:是的,你可以一>.
推荐答案
从 MongoDB v2.5.3 开始,有一个新的 $position
运算符,您可以将其与 $each
运算符作为 $push
查询的一部分,用于指定数组中要插入值的位置.
As of MongoDB v2.5.3, there is a new $position
operator that you can include along with the $each
operator as part of your $push
query to specify the location in the array at which you would like to insert a value.
这是文档页面中的示例,用于在数组索引 2 处添加元素 20 和 30::
Here's an example from the docs page to add the elements 20 and 30 at the array index of 2::
db.students.update( { _id: 1 },
{ $push: { scores: {
$each: [ 20, 30 ],
$position: 2
}
}
}
)
参考:http://docs.mongodb.org/master/reference/operator/update/position/#up._S_position
这篇关于你可以让 mongo $push prepend 而不是 append 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!