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
How do I delete array value from a document in MongoDB?
To delete array values, use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Let us first create a collection with documents −
> db.demo535.insertOne(
... {
...
... "studentId" : "101",
... "studentName" : "Chris",
... "ListOfMailIds" : [
... "Chris@gmail.com",
... "Chris@yahoo.com"
... ]
...
... }
... )
{
"acknowledged" : true,
"insertedId" : ObjectId("5e8c82bfef4dcbee04fbbc00")
}
Display all documents from a collection with the help of find() method −
> db.demo535.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c82bfef4dcbee04fbbc00"), "studentId" : "101", "studentName" : "Chris",
"ListOfMailIds" : [ "Chris@gmail.com", "Chris@yahoo.com" ] }
Following is the query to delete array value from a document in MongoDB −
> db.demo535.update(
... { _id: ObjectId("5e8c82bfef4dcbee04fbbc00") },
... { $pull: { 'ListOfMailIds': 'Chris@yahoo.com' } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo535.find();
This will produce the following output −
{ "_id" : ObjectId("5e8c82bfef4dcbee04fbbc00"), "studentId" : "101", "studentName" : "Chris", "ListOfMailIds" : [ "Chris@gmail.com" ] }Advertisements