Don't explicitly create a collection#932
Conversation
…y when a document is inserted. Trying to explicity create a collection that exists causes an exception in pymongo.
Imran-imtiaz48
left a comment
There was a problem hiding this comment.
Review:
The code snippet efficiently handles MongoDB operations by performing conditional checks to rename, create, or drop collections based on the provided inputs. The renameCollection command is appropriately used to rename collections if both a and b are specified. The logic for creating collections is also well-implemented; it verifies if the create key exists in the document and maps the collection using map_collection before creating it. Similarly, for dropping collections, the presence of the drop key is checked, and the appropriate collection is dropped if the mapping is successful.
Recommendation:
While the code is functional and handles MongoDB operations as intended, consider consolidating and refactoring the repetitive code blocks to improve readability and maintainability. For instance, you could extract the common operations for renaming, creating, and dropping collections into separate methods or utility functions. This approach would reduce redundancy and make it easier to manage changes or enhancements in the future. Additionally, ensure that error handling and logging are implemented to capture any potential issues during these operations, which would enhance the robustness of the code.
Problem
We have various
mongoservers that we sync with a central server usingmongo-connectorwith themongo_doc_manager.They all sync into the same collection on the central server.
When a new system is initialized, it has nothing in the DB and
mongo-connectoris running.When the first entry is made into the local DB, there is an oplog entry to
createthe collection. Whenmongo-connectortries to replay that command on the target DB,pymongothrows an exception because the collection already exists on the central server.Note: this problem does not present itself if
mongo-connectoris started (without an existingoplog.timestamp) after the first entry in the local collection has already been made.Solution
This problem is easily avoided by not trying to explicitly create the collection, effectively ignoring the
createentry in the oplog.This does not cause any problems because
mongocreates collections automatically whenever a document is inserted into a collection that does not yet exist. The only reason to explicitly create a collection is if special options are specified as per the documentation:Since
mongo_doc_managerdoes not specify any options in thecreate_collection()call, that call should not be made.