我想在我的设置开始时添加push而不是在我执行mongo $ push时附加到结尾.
是否可以进行原子推送更新,将元素添加为第一个而不是最后一个?
2014年更新:是的,你可以.
Ser*_*tin 28
使用带有$ set的负索引进行前置,在mongo v2.2中进行测试:
> db.test.insert({'array': [4, 5, 6]})
> db.test.find()
{ "_id" : ObjectId("513ad0f8afdfe1e6736e49eb"),
"array" : [ 4, 5, 6 ] }
//prepend 3
> db.test.update({"_id" : ObjectId("513ad0f8afdfe1e6736e49eb")},
{'$set': {'array.-1': 3}})
> db.test.find()
{ "_id" : ObjectId("513ad0f8afdfe1e6736e49eb"),
"array" : [ 3, 4, 5, 6 ] }
//prepend 2
> db.test.update({"_id" : ObjectId("513ad0f8afdfe1e6736e49eb")},
{'$set': {'array.-1': 2}})
> db.test.find()
{ "_id" : ObjectId("513ad0f8afdfe1e6736e49eb"),
"array" : [ 2, 3, 4, 5, 6 ] }
//prepend 1
> db.test.update({"_id" : ObjectId("513ad0f8afdfe1e6736e49eb")},
{'$set': {'array.-1': 1}})
> db.test.find()
{ "_id" : ObjectId("513ad0f8afdfe1e6736e49eb"),
"array" : [ 1, 2, 3, 4, 5, 6 ] }
Run Code Online (Sandbox Code Playgroud)
Ted*_*ery 27
从MongoDB v2.5.3开始,有一个新的$position运算符,您可以将其$each作为$push查询的一部分与运算符一起包含,以指定要在其中插入值的数组中的位置.
这是一个来自docs页面的示例,用于在数组索引2处添加元素20和30 ::
db.students.update( { _id: 1 },
{ $push: { scores: {
$each: [ 20, 30 ],
$position: 2
}
}
}
)
Run Code Online (Sandbox Code Playgroud)
参考:http://docs.mongodb.org/master/reference/operator/update/position/#up._S_position
几天前也提出了类似的问题.不幸的是,简短的回答是"不",但是对此功能有一个公开请求.
https://jira.mongodb.org/browse/SERVER-2191 - "$ push()到数组的前面"
在另一个线程上有一些更多的信息以及可能的解决方法:"使用MongoDB数组作为堆栈" - 使用MongoDB数组作为堆栈
希望以上内容对您有所帮助并帮助您找到可接受的解决方法.