2

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
   ]
}

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.