Separate queries in MongoDB with ;

Quick question.

I have a number of update commands to run on my MongoDB database. These happen after a user has completed a number of tasks and wants to push all updates to the server. I will update several documents in several collections.

If I want to assure that these updates are atomic and no other simultaneous queries or commands from other users can interfere, can I separate my queries with ; ?

Simplified example:

db.cities.find({"asciiname":"Zamin Sukhteh"});db.cities.find({"asciiname":"Konab-e Vasat"})

Will the above result in two separate and atomic queries?


While you can't use a delimiter to separate commands in the shell to introduce atomicity, you can use db.eval.

If you're only using the shell (which you said in comments), you can use the db.eval function to perform a database-wide lock while executing a block of JavaScript code. It's not something you'd normally want to do (as it blocks all writes and reads by default), but in the case that you're describing above (again, the comments), it sounds like it would fit your needs.

db.eval( function() {
    var one = db.cities.find({"asciiname":"Zamin Sukhteh"});
    var two = db.cities.find({"asciiname":"Konab-e Vasat"});
    // other work ...
});

Update (to address a comment):

If you want efficient atomic (-like) updates in MongoDB, there are a few options:

  • Put everything in a single document. This is guaranteed atomic in MongoDB. However, that often doesn't work for complex document models (or large documents).
  • If there are dependencies on a document, consider placing new "versions" of the dependent documents, and then, only after those are all set, put the final document linking those documents together into the DB. Without the final "link", older documents shouldn't see the new versions. Depending on how the data is consumed, it's likely you could remove the older versions quite rapidly (or periodically if desired).
  • Accept that there will occasionally be mismatches and detect them (and then rerun the query to get fresh data). You might be able to use a timestamp or version to identify these cases as you traverse through your document structure.
  • Cache the data elsewhere as a full-structure for common queries
  • Decide MongoDB isn't a good fit for your requirements.
  • 链接地址: http://www.djcxy.com/p/61944.html

    上一篇: 使用MongoDB的官方C#驱动程序进行按位枚举(标志)查询

    下一篇: 在MongoDB中单独查询;