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

Susan Sarandon
Release: 2024-10-30 11:10:00
Original
246 people have browsed it

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})
Copy after login

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>
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!