yuji itadori
yuji itadori

Reputation: 19

How to update the array objects if id exist otherwise insert in mongodb

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

Upvotes: 0

Views: 32

Answers (2)

fayas_akram
fayas_akram

Reputation: 116

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
)

Upvotes: 0

Osiyomeoh
Osiyomeoh

Reputation: 72

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},
 )

Upvotes: 1

Related Questions