How does $addToSet specify a field as a check field for existence

  mongodb, question

There is a document, one of its attributes is a document array. I want to add a document to the array. If there is one, it will not be added. How is the judgment here made? Is all attributes the same? Can you specify an attribute
For example, in the above record, I want to add data to user. if id is 1, it means that it already exists, then it will not be added, otherwise it will be added to user array
Can $addToSet fulfill this requirement?
Thank you

The uniqueness of the sub document you need, $addToSet can’t do it either. There are two ideas for reference:

1. Try whether a composite unique index can be created in business

For example, create a unique composite index on the name and of the text {_ id, name, number, user [{id, name}]}

2. Code Control

db.test.update({ "_id" : ObjectId(""), "" : {$ne : value }}, {$push : { user : { id : 1 , name : "a" }}})
 db.test.update({ "_id" : ObjectId(""), "" : {$nin : [] }}, {$push : { user : { id : 1 , name : "a" }}})

Before updating, use $ne or $nin to determine whether exists in the existing id before updating.

For reference.

Love MongoDB´╝ü Have Fun!