how do i add a value to the top of an array in mongodb?

后端 未结 2 2005
盖世英雄少女心
盖世英雄少女心 2020-12-06 06:50

how do i add a value to the top of an array in mongodb?

say i have this document in my mongo collection:

{ \"colors\" : [ \"red\", \"green\", \"blue\         


        
2条回答
  •  死守一世寂寞
    2020-12-06 07:54

    "unshift" inserts data in the front of an array.. whereas "push" inserts it at the end. e.g. in JavaScript:

    > a = ['red','green','blue']
    [ "red", "green", "blue" ]
    > a.unshift("yellow")
    4
    > a
    [ "yellow", "red", "green", "blue" ]
    

    But unfortunately this isn't supported by the Mongo API as an atomic operation:

    http://www.mongodb.org/display/DOCS/Updating

    it just supports "push"


    How big is your array?

    you could ether assume that your array in Mongo is always stored in reverse, and use push, or you could read-out the array, modify it with unshift, and then store it again (which wouldn't be atomic though)

提交回复
热议问题