MongoDB
 sql >> Base de données >  >> NoSQL >> MongoDB

comment mettre à jour le numéro de séquence dans mongodb en toute sécurité

Pour ce faire de manière atomique, vos trois exemples de documents doivent faire partie du même document. MongoDB n'effectue des opérations de manière atomique que sur des documents simples :http://www.mongodb.org/ display/DOCS/Atomic+Operations

S'ils font partie d'un seul document, ce qui suit modifierait l'ordre des 2e et 3e sous-documents :

> db.so.find().pretty();{ "_id" :ObjectId("4f55e7ba362e2f2a734c92f8"), "subs" :[ { "author_id" :"a", "class" :"principe", "content_id" :null, "host_id" :null, "modified_date" :1330935540, "order" :1, "pub_date" :1330935540, "score" :0, "text" :"Hello World!", "vote_down_count" :0, "vote_up_count" :0 }, { "author_id" :"a", "class" :"principle", "content_id" :null, "host_id" :null, "modified_date" :1330935538, "order" :2, "pub_date" :1330935538, "score" :0, "text" :"Ravi de vous rencontrer.", "vote_down_count" :0, "vote_up_count" :0 }, { "author_id" :"a", "class" :"principe", "content_id" : null, "host_id" : null, "modified_date" :1330935548, "order" :3, "pub_date" :1330935548, "score" :0, "text" :"Génial !", "vote_down_count" :0, "vote_up_count" :0 } ]}

Requête :

db.so.update( { _id:new ObjectId("4f55e7ba362e2f2a734c92f8")}, { $set :{ 'subs.1.order' :3, 'subs.2.order' :2 } }); 

Résultat :

> db.so.find().pretty();{ "_id" :ObjectId("4f55e7ba362e2f2a734c92f8"), "subs" :[ { "author_id" :"a", "class" :"principe", "content_id" :null, "host_id" :null, "modified_date" :1330935540, "order" :1, "pub_date" :1330935540, "score" :0, "text" :"Hello World!", "vote_down_count" :0, "vote_up_count" :0 }, { "author_id" :"a", "class" :"principle", "content_id" :null, "host_id" :null, "modified_date" :1330935538, "order" :3, "pub_date" :1330935538, "score" :0, "text" :"Ravi de vous rencontrer.", "vote_down_count" :0, "vote_up_count" :0 }, { "author_id" :"a", "class" :"principe", "content_id" : null, "host_id" : null, "modified_date" :1330935548, "order" :2, "pub_date" :1330935548, "score" :0, "text" :"Génial !", "vote_down_count" :0, "vote_up_count" :0 } ]}