0

I have this data in database.

{
   "_id" : ObjectId("5a6ef287370ff5dc3d6fda7b"),
   "name" : "Jhones Crows",
   "hobbies" : [ 
      {
        "name" : "swim",
        "_id" : ObjectId("5a6ef287370ff5dc3d6fda7b")
      }, 
      {
        "name" : "run",
        "_id" : ObjectId("5a6ef287370ff5dc3d6fda7c")
      }
   ]
}

And I try to add data into hobbies if data in hobbies not exist. I try this :

db.getCollection('milo').update(
{'_id' : ObjectId("5a6ef287370ff5dc3d6fda7b"), 'hobbies.name' : 'sport'},
{ $addToSet : { 'hobbies' : {
    'name' : 'sport',
}}
},
{upsert : true}
)

And I want data result like this :

{
   "_id" : ObjectId("5a6ef287370ff5dc3d6fda7b"),
   "name" : "Jhones Crows",
   "hobbies" : [ 
      {
        "name" : "swim",
        "_id" : ObjectId("5a6ef287370ff5dc3d6fda7b")
      }, 
      {
        "name" : "run",
        "_id" : ObjectId("5a6ef287370ff5dc3d6fda7c")
      },
      {
        "name" : "sport",
        "_id" : ObjectId("5a6ef287370ff5dc3d6fda7a")
      }
   ]
}

so suppose the value of sport is not in hoobies.name. will add a new name object in the hobbies. but if there is not change anything

kyty
  • 76
  • 1
  • 9
  • Try `db.getCollection('milo').update( {'_id' : ObjectId("5a6ef287370ff5dc3d6fda7b"), 'hobbies.name' : {$ne:'sport'}}, { $addToSet : { 'hobbies' : { 'name' : 'sport', }} }, {upsert : true} )` – s7vr Jan 29 '18 at 11:29
  • Possible duplicate of [Can you specify a key for $addToSet in Mongo?](https://stackoverflow.com/questions/14527980/can-you-specify-a-key-for-addtoset-in-mongo) – s7vr Jan 29 '18 at 11:34
  • This works very great . I don't know that there is $ne in mongodb. – kyty Jan 29 '18 at 12:47
  • thank you Veeram. you are very helpful – kyty Jan 29 '18 at 12:48

0 Answers0