Narayansingh Rajput
Narayansingh Rajput

Reputation: 323

Failed to uniqueindex while updating subdocument in mongodb?

Following is my db structure

{"dname" : "a",   "accounts" : [
        {
          'userId':'1',
          'name':'xyz'
         }
     ] 
 }

As i've added uniqueindex dname_1,dname_1_accounts.userId_1 to collection but when in update when i use push query as below

{$push:{"accounts" :{'userId':'1','name':'abc'}}}

or

{$addToSet:{"accounts" :{'userId':'1','name':'abc'}}}

It doesn't give error of unique key or any kind it adds duplicate key value to document

{"dname" : "a",   "accounts" : [
            {
              'userId':'1',
              'name':'xyz'
             },
             {
              'userId':'1',
              'name':'abc'
             }

         ] 
     }

how to avoid this issue using nativemongo querys?

Upvotes: 0

Views: 35

Answers (2)

Narayansingh Rajput
Narayansingh Rajput

Reputation: 323

db.coll.update({"dname" : "a","accounts.userId" :{$ne:'1'}},{$push:{"accounts" :{'userId':'1','name':'abc'}}})

this will not give error but it also avoid inserting duplicates with key userId in the accounts array

Upvotes: 1

Martin Konecny
Martin Konecny

Reputation: 59681

Because your userId is stored inside of an accounts, your index would need to be on

accounts.userId

Run

db.coll.createIndex( { 'accounts.userId': 1 }, { unique: true } )

and your second insert statement should now fail.

Upvotes: 1

Related Questions