@lew
There are a few ways to prevent the insertion of duplicate documents in a MongoDB collection:
- Use a unique index: You can create a unique index on one or more fields in your collection to enforce uniqueness. This will prevent any new documents with duplicate values in the indexed fields from being inserted.
1
|
db.collection.createIndex({ field1: 1, field2: 1 }, { unique: true });
|
- Use the $addToSet operator: If you are updating a document and want to add a new value to an array field, you can use the $addToSet operator. This will only add the new value if it does not already exist in the array.
1
|
db.collection.update({ _id: ObjectId("document_id") }, { $addToSet: { arrayField: "new_value" } });
|
- Use the upsert option: When performing an update operation, you can use the upsert option to insert a new document if no document matches the query criteria. This can help prevent the insertion of duplicate documents.
1
|
db.collection.update({ field: "value" }, { field: "value" }, { upsert: true });
|
By utilizing these methods, you can effectively prevent the insertion of duplicate documents in a MongoDB collection.