Home > Software engineering >  How unique items in array filed of documents in mongoDB
How unique items in array filed of documents in mongoDB

Time:12-29

I want my user to have a unique address name in MongoDB.

user: {
   name: ...,
   addresses: [
   {name: "address1",...},
   {name: "address2",...}
    ]
}

if the user adds a duplicate address's name, he gets an error.

CodePudding user response:

In this scenario, you cannot use the MongoDB index because the unique constraint index uses for different documents, not for an array in each document.

You can use a trick to prevent your DB, adding multiple same names as addresses in a user document:

db.users.updateOne({"user_identifier": <user_identifier>
                    "addresses": {
                           "$not": {
                              "$elemMatch": {
                                 "name": <new_address_name>
                              }
                           }
                    },
                   {"$push": {"addresses": <new_address>}}
)

In the first step, this query found a user that matches your identifier and doesn't have the new address name. So if your user has an address with the new name, your query doesn't match with any user and no users will be updated.

  • Related