1

Suppose I have an object in mongoDB:

collection_name: book_info

{_id:"121as", "book_num":"12a", "book_name":"lotr", "info":[ {"borrowerAddress":["NY","Delhi"] }, 
{"borrowerAddress":["SI","Ghana"] } ] }

I want to delete an element "NY" from info.

For this I can do is fetch the object from book_info collection and apply loop and delete when element found inside array and save the data into db.

But I want to do is delete and update at same time without fetching data and looping and updating again.

Also, if direct db manipulation is possible, can anyone suggest me whether fetching data, applying loop and deleting data is efficient or deleting data from db directly is more faster, based on solutions provided.

If anyone needs any further information, please let me know.

Additional Question:

doc1: {_id:"121as", "book_num":"12a", "book_name":"lotr", "info":[ {"borrowerAddress":["NY","Delhi"] }, 
{"borrowerAddress":["SI","Ghana"] } ] }

doc2: {_id:"213s", "book_num":"1c", "book_name":"hp", "info":[ {"borrowerAddress":["NY","Delhi"] }, 
{"borrowerAddress":["SI","Ghana"] } ] }

Assume I have multiple documents inside a book_info collection with different book names and details and I want to delete document for "book_name":"lotr" only, I delete address "NY" from document.

1 Answer 1

3

You can try update query with $pull operator to remove matching element from array, $[] positional for all elements in info array,

db.collection.update(
  { "info.borrowerAddress": "NY" },
  { $pull: { "info.$[].borrowerAddress": "NY" },
  { multi: true }
})

Playground


Assume I have multiple documents inside a book_info collection with different book names and details and I want to delete document for "book_name":"lotr" only, I delete address "NY" from document.

db.collection.update(
  { "book_name":"lotr", "info.borrowerAddress": "NY" },
  { $pull: { "info.$[].borrowerAddress": "NY" },
  { multi: true }
})

Playground

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you so much for your help. But I'm unable to understand what is going on. Could you please tell me, what exactly is happening?
Can I ask question related to this? Or should I create new question?
yes you can ask here if its related to this question.
I have edited my original question, and added additional question. Could you please have a look? In case need any additional information please let me know.
I want to fetch document "book_name":"lotr" only, I want to delete address "NY" exactly not getting this, do you want to select data or remove elements?
|

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.