There is a document, and one of its attributes is a document array. I want to add a document to the array. If it exists, it will not be added. How to judge whether it exists or not is that all attributes are the same. ? Can you specify an attribute
{_id:0,
user:[{id:1,name:a}]
}
For example, for the above record, I want to add data to user , if the id is 1, it means it already exists, so it will not be added, otherwise it will be added to the user array
$addToSet can achieve this requirement
Thank you
The uniqueness of the sub document you need cannot be achieved by $addToSet. There are two ideas for reference:
1. Try to create a composite unique index for business purposes
For example: create a unique composite index on name and user.id of the text {_id, name, number,user[{id,name}]}
2. Code control
Use $ne or $nin before updating to determine whether the user.id exists in the existing id. If it does not exist, you can update.
For reference.
Love MongoDB! Have Fun!