44

当我执行 mongo $push 时,我希望在集合的开头添加 push 添加而不是附加到末尾。

是否可以进行原子推送更新,将元素添加为第一个而不是最后一个?


2014 更新是的,你可以

4

3 回答 3

33

从 MongoDB v2.5.3 开始,$position您可以将一个新的运算符与该$each运算符一起包含在$push查询中,以指定数组中您要插入值的位置。

这是文档页面中的一个示例,用于在数组索引 2 处添加元素 20 和 30::

db.students.update( { _id: 1 },
                    { $push: { scores: {
                                         $each: [ 20, 30 ],
                                         $position: 2
                                       }
                             }
                    }
                  )

参考:http ://docs.mongodb.org/master/reference/operator/update/position/#up._S_position

于 2013-11-13T06:13:41.237 回答
29

使用带有 $set 的负索引作为 prepend,在 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 ] }
于 2013-03-09T06:14:32.933 回答
5

前几天有人问过类似的问题。不幸的是,简短的回答是“不”,但对此功能有一个开放的请求。
https://jira.mongodb.org/browse/SERVER-2191 - “$push() 到数组前面”

在另一个线程上有更多信息以及可能的解决方法:“使用 MongoDB 数组作为堆栈” -使用 MongoDB 数组作为堆栈

希望以上内容对您有用并帮助您找到可接受的解决方法。

于 2012-04-12T21:27:53.190 回答