How to delete element from an array in MongoDB?

MongoDBDatabaseBig Data Analytics

To delete element from an array, use $pull. Let us create a collection with documents −

> db.demo279.insertOne({id:[101,103,105,110]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e490af7dd099650a5401a58")
}
> db.demo279.insertOne({id:[107,111,110]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e490b06dd099650a5401a59")
}

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

> db.demo279.find();

This will produce the following output −

{ "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105, 110 ] }
{ "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111, 110 ] }

Following is the query to delete element from an array &minus';

> db.demo279.update({},{$pull:{id:110}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

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

> db.demo279.find();

This will produce the following output −

{ "_id" : ObjectId("5e490af7dd099650a5401a58"), "id" : [ 101, 103, 105 ] }
{ "_id" : ObjectId("5e490b06dd099650a5401a59"), "id" : [ 107, 111 ] }
raja
Published on 31-Mar-2020 16:51:32
Advertisements