Home  >  Article  >  Backend Development  >  How to Prevent Duplicate Documents in MongoDB After Unique Key Addition?

How to Prevent Duplicate Documents in MongoDB After Unique Key Addition?

Susan Sarandon
Susan SarandonOriginal
2024-10-30 11:10:00246browse

How to Prevent Duplicate Documents in MongoDB After Unique Key Addition?

Preventing Duplicate Documents in MongoDB after Unique Key Addition

Despite adding a unique index on the uid and sid fields (db.user_services.createIndex({"uid":1 , "sid": 1},{unique:true,dropDups: true})), duplicate documents may still be inserted due to a limitation in MongoDB 3.0.0.

To eliminate existing duplicates, a custom procedure can be used:

db.events.aggregate([
    { "$group": {
        "_id": { "uid": "$uid", "sid": "$sid" },
        "dups": { "$push": "$_id" },
        "count": { "$sum": 1 }
    }},
    { "$match": { "count": { "$gt": 1 } }}
]).forEach(function(doc) {
    doc.dups.shift();
    db.events.remove({ "_id": {"$in": doc.dups }});
});

db.events.createIndex({"uid":1 , "sid": 1},{unique:true})

This procedure removes duplicates, allowing the unique index to be created as intended.

Emulating MySQL's "ON DUPLICATE KEY" Behavior

To achieve the behavior of MySQL's insert (value) on duplicate key update rate=rate 1 using PHP, the update() method with the upsert option can be employed:

<code class="php">$collection->update(
    ["uid" => 1, "sid" => 1],
    [
        '$set' => [
            "field" => "this",
            "counter" => 1  // Incrementing the "counter" field by 1
        ],
        '$setOnInsert' => [
            "newField" => "another"
        ]
    ],
    ["upsert" => true]
);</code>

Using the $inc operator, the rate field can be incremented:

<code class="php">[
    '$inc' => [
        "rate" => 1
    ]
],</code>

The above is the detailed content of How to Prevent Duplicate Documents in MongoDB After Unique Key Addition?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn