How to remove element in a MongoDB array?

MongoDBDatabaseBig Data Analytics

To remove an element, update, and 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.demo541.insertOne({"software":{"services":["gmail","facebook","yahoo"]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ca845ef4dcbee04fbbc11")
}
> db.demo541.insertOne({"software":{"services":["whatsapp","twitter"]}});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8ca85cef4dcbee04fbbc12")
}

Display all documents from a collection with the help of find() method −

> db.demo541.find();

This will produce the following output −

{ "_id" : ObjectId("5e8ca845ef4dcbee04fbbc11"), "software" : { "services" : [ "gmail", "facebook", "yahoo" ] } }
{ "_id" : ObjectId("5e8ca85cef4dcbee04fbbc12"), "software" : { "services" : [ "whatsapp", "twitter" ] } } 

Following is the query to remove an element in a MongoDB array −

> db.demo541.update({ _id: ObjectId("5e8ca845ef4dcbee04fbbc11") },
...    { $pull: { 'software.services': "yahoo" }}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo541.find();

This will produce the following output −

{ "_id" : ObjectId("5e8ca845ef4dcbee04fbbc11"), "software" : { "services" : [ "gmail", "facebook" ] } }
{ "_id" : ObjectId("5e8ca85cef4dcbee04fbbc12"), "software" : { "services" : [ "whatsapp", "twitter" ] } }
raja
Published on 14-May-2020 06:47:53
Advertisements