Home > Software design >  How to update the array objects if id exist otherwise insert in mongodb
How to update the array objects if id exist otherwise insert in mongodb

Time:01-20

I have an user document in database.

users: [
  {
     id: 3435,
     userName: "User name",
     books: [
        {
           id: 5453, 
           bookId: 123,
           name: "Book name", 
           authors: [{
               country: "USA"
               name: "Author name"
           }]}
     ]
  }
]

what i need to do is insert new book data to books array if the book is not exist. but if exist i want to update the book data of that specific book.

How I can achive this in mongo

CodePudding user response:

Alright do this to update or insert if it's not there

db.posts.update({book: [array you want to update]},
     {New Array},
         {upsert: true},
 )

CodePudding user response:

Use $exist to verify if the field exists and use upsert=true to insert if the field is not exist.

mongo query format like below! db.collection.update(query, update, options)

Answer is ..

db.getCollection('user').update(
 {
    books: {$exists: true},
    id: '54'

 }, 
 {
    $set: 
       books:[  
        {
           id: 5453, 
           bookId: 123,
           name: "Book name", 
           authors: [{
               country: "USA"
               name: "Author name"
           }]} 
    ]

   
 },
    upsert=True
)
  •  Tags:  
  • Related