
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove String from Array in MongoDB Document
You can use $pull operator to remove a string from an array. Let us first create a collection with documents −
> db.removeAStringDemo.insertOne({"Score":[45,67,89,"John",98,99,67]}); { "acknowledged" : true, "insertedId" : ObjectId("5cda5224b50a6c6dd317adbd") }
Following is the query to display all documents from a collection with the help of find() method −
> db.removeAStringDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cda5224b50a6c6dd317adbd"), "Score" : [ 45, 67, 89, "John", 98, 99, 67 ] }
Following is the query to remove a string from an array in a MongoDB document. The string which is to be removed is “John” −
> db.removeAStringDemo.update( { _id :ObjectId("5cda5224b50a6c6dd317adbd") }, { $pull: { "Score":"John" }}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the document once again −
> db.removeAStringDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cda5224b50a6c6dd317adbd"), "Score" : [ 45, 67, 89, 98, 99, 67 ] }
Advertisements