John
John

Reputation: 2761

Add new document into an array if there is no same field value in any other array embedded document

I have a document

{
   _id:1,
   persons:[
     {name:"Jack", age:10},
     {name:"Ma",age:20}

   ]

}

I want to push new document {name:"Ho",age;22} in persons array. But there is a condition- the new document will be added to array if name name:"Ho" does not exist in other embedded array documents. If exists, {name:"Ho",age;22} will not be added to persons array. What is the way?

Upvotes: 1

Views: 46

Answers (2)

thammada.ts
thammada.ts

Reputation: 5245

You can use the $not operator along with $elemMatch to query the document that doesn't a person with that name.

Your update would look like this

db.collection.update({
  _id: 1,
  persons: {
    $not: { $elemMatch: { name: "Ho" } }
  }
}, { $push: { persons: { name: "Ho", age: 30 } } })

Upvotes: 1

John
John

Reputation: 2761

This works for me

db.collection('test').update({
  _id: 1,
  "persons.name" : {$ne:"Ho"}
}, { $push: {persons: { name: "Ho", age: 30 } }  })

Upvotes: 1

Related Questions