How to upload non-duplicate JSON data in Azure Cosmos DB using mongodb API?

Viewed 167
     try {

            db.collection('student').createIndex({"student_id": 1} ,{ unique: true });
    
            db.collection('student').insertOne({student_id:req.body.student_id},{ upsert: true });

            console.log("Document Inserted")
        } catch (error) {
            console.log(error)
            return res.status(400).send({
                message: 'Unable to insert data',
                errors: error,
                status: 400
               })

        }

    });
}

I applied unique:true and upsert:true but its not working it uploads duplicate data every time.

1 Answers

I think you can follow my steps to check if it has created correct unique index for your cosmos mongoapi. Pls note, unique index can be created when the collection has no document. So if you try to add unique index, you may delete and create a new collection first.

First, you need to check if you've created unique index correctly. Go to your database in azure portal, open console panel in your browser(press F12), then open the setting view, see my screenshot below:

enter image description here

If the unique index exists, I think it will be ok for your program to prevent insert duplicate item. At least in my side it worked well. I'll show my code here, you may refer to it.

enter image description here

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'copy from quick start-> nodejs-> PRIMARY CONNECTION STRING';

var createUniqueIndex = function(db){
    db.collection('families').createIndex({"lastName": 1} ,{ unique: true });
    console.log("============create index succssfully============");
}

var insertDocument = function(db, callback) {
db.collection('families').insertOne( {
        "id": "AndersenFamily2",
        "lastName": "Andersen",
        "parents": [
            { "firstName": "Thomas" },
            { "firstName": "Mary Kay" }
        ],
        "children": [
            { "firstName": "John", "gender": "male", "grade": 7 }
        ],
        "pets": [
            { "givenName": "Fluffy" }
        ],
        "address": { "country": "USA", "state": "WA", "city": "Seattle" }
    }, function(err, result) {
    assert.equal(err, null);
    console.log("Inserted a document into the families collection.");
    callback();
});
};

MongoClient.connect(url, function(err, client) {
    assert.equal(null, err);
    var db = client.db('familiesdb');
    // createUniqueIndex(db);
    insertDocument(db, function() {
        client.close();
    });
});
Related