有个文档,它的一个属性,是一个文档数组,我想往数组里面添加一个文档,如果存在,则不添加,这里的判断是否存在是如何判断的,是所有属性都相同才算?能不能指定一个属性{_id:0,user:[{id:1,name:a}]}比如,上面这条记录,我想往user里面添加数据,如果id为1,则表示已经存在,则不添加,否则就添加到user数组中$addToSet能实现这种需求不谢谢
ringa_lee
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
db.test.update({ "_id" : ObjectId(""), "user.id" : {$ne : value }}, {$push : { user : { id : 1 , name : "a" }}}) db.test.update({ "_id" : ObjectId(""), "user.id" : {$nin : [] }}, {$push : { user : { id : 1 , name : "a" }}})
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!
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!