mongodbmongodb-querynosqlaggregation-frameworkmongodb-indexes

How to generate unique id for each element of an array field in MongoDB


  1. How to create a unique ID for each element of an array field, where uniqueness is maintained globally for all documents of the collection?

  2. Is it possible to specify create a unique index for this field?


Solution

  • You can make use of ObjectId data type. ObjectIds are 12-byte values that are guaranteed to be unique across all documents in a collection. You can specify an ObjectId as the value for a field in an array when inserting a new document.

    For example, if you have following document:

    {
        _id: ObjectId("5f9b5a6d65c5f09f7b5a6d65"),
        nameOfArrayField: []
    }
    

    You can use the following command to insert a new document:

    db.collection.insertOne({
        nameOfArrayField: [
            {
                id: new ObjectId(),
                name: "Big Cat Public Safety Law"
            }
        ]
    });
    

    To specify a unique index, you can use createIndex() method in the MongoDB shell.

    db.collection.createIndex({ "nameOfArrayField.id": 1 }, { unique: true })
    

    unique: true option ensures that the id field of the element array will be unique globally for all documents of the collection. It will prevent from inserting the duplicate element with the same id field in the array. Point to be noted that it is an asynchronous operation. You can use the db.collection.getIndexes() method to check if the index is created or not.