jef
jef

Reputation: 4075

Mongodb: How to add unique value to each element in array?

I'm a new user of mongodb and I have a model like below. For update list data, I have to specify the element in an array. So I think I need to store a unique value for each element. Because list.name and list.price are variable data.

So are there any good ways to create an unique id in mongodb? Or should I create unique ids by myself?

{
   name: 'AAA',
   list: [
     {name: 'HOGE', price: 10, id: 'XXXXXXXXXX'}, // way to add id
     {name: 'FUGA', price: 12, id: 'YYYYYYYYYY'}  // way to add id
   ]
}

Upvotes: 2

Views: 3384

Answers (3)

Shashank Mistry
Shashank Mistry

Reputation: 209

whoever is seeing this in 2022, mongodb creates unique ids automatically we just have to provide schema for that particular array. like,

 _id : {
        type: String
    },
    list: {
        type: [{
            Name : {
                type: String
            },
            price : {
                type: String
            }
        }]
    }

this schema will generate auto id for all elements added into array but below example will not create it.

 _id : {
        type: String
    },
    list: {
        type: Array
    }

Upvotes: 0

britishgreenworm
britishgreenworm

Reputation: 16

use ObjectId() on your id field, so like..

db.test.update({name: "AAA"}, { $push: { list: {_id : ObjectId(), name: "dingles", price: 21} }});

reference: https://docs.mongodb.org/v3.0/reference/object-id/

Upvotes: 0

PaulShovan
PaulShovan

Reputation: 2134

Mongodb creates unique id only for documents. There is no better way for list or array elements. So, you should create Unique ids yourself.

Add keep in mind that, While updating your list use $addToSet. For more information of $addToSet follow this documentation

Upvotes: 1

Related Questions