0

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

2 Answers 2

1

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},
 )
Sign up to request clarification or add additional context in comments.

Comments

0

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.