search

Home  >  Q&A  >  body text

mongodb - How does $addToSet specify a field as a check field for existence?

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

ringa_leeringa_lee2788 days ago927

reply all(1)I'll reply

  • 世界只因有你

    世界只因有你2017-05-02 09:27:30

    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!

    reply
    0
  • Cancelreply