clint
clint

Reputation: 14524

MongoDB: How to prevent read access while a collection is emptied and re-populated?

I have a MongoDB (v2.2.0) collection that contains "reference data". Periodically, I need to replace all the documents in that collection with data from an outside source. It's important that nothing accesses the collection while the reference data is being replaced.

Am I correct in thinking the best solution to simply create a new (i.e., "temporary") collection with a different name, load it with data, then rename it?

For example:

  1. Create collection myCollection-TEMP
  2. Insert all documents into myCollection-TEMP
  3. Rename the temp collection to replace (i.e., drop prior to the rename) the current collection db.myCollection-TEMP.renameCollection('myCollection', true)

From what I can tell, there's no way to safely "empty" a collection, do a "bulk import" of documents, and ensure nothing else accesses the collection in the middle of that process.

Upvotes: 0

Views: 105

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230316

Yes, creating a temp collection and then renaming is the way to go. This is a common approach in other technologies as well. For example, double buffering in computer graphics. You prepare a frame in an invisible background plane and then just swap it with the screen. This instantly updates the picture without flicker or other artifacts.

Upvotes: 1

Related Questions