从MongoDB v2.5.3开始,有一个新的$position
运算符,您可以将其与$each
运算符一起作为$push
查询的一部分包含在内,以指定要插入值的数组位置。
以下是文档页面上添加元素20和30到索引为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
$each
? - Константин Ван使用$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 ] }
$push - $each - $position: 0
的语法了。能否请你更新一下被接受的答案?同时,由于这种语法很奇怪,请通过在此问题上投票来帮助实现$unshift
(https://jira.mongodb.org/browse/SERVER-19974)。 - Dan Dascalescu