Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

arrays - Can you have mongo $push prepend instead of append?

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 update: yes you can.

question from:https://stackoverflow.com/questions/10131957/can-you-have-mongo-push-prepend-instead-of-append

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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
                                       }
                             }
                    }
                  )

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...