How to pull an array element (which is a document) in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use $pull operator. Let us first create a collection with documents −

> db.pullAnArrayElementDemo.insertOne( { "StudentDetails": [ { "StudentFirstName":"Chris","StudentScore":56 }, {"StudentFirstName":"Robert","StudentScore":59 } ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd3b55bedc6604c74817cd5")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.pullAnArrayElementDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd3b55bedc6604c74817cd5"),
   "StudentDetails" : [
      {
         "StudentFirstName" : "Chris",
         "StudentScore" : 56
      },
      {
         "StudentFirstName" : "Robert",
         "StudentScore" : 59
      }
   ]
}

Following is the query to pull an array element (which is a document) in MongoDB −

>db.pullAnArrayElementDemo.update({},{$pull:{'StudentDetails':{'StudentFirstName':'Chris'}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us display all the documents once again. The query is as follows −

> db.pullAnArrayElementDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd3b55bedc6604c74817cd5"),
   "StudentDetails" : [
      {
         "StudentFirstName" : "Robert",
         "StudentScore" : 59
      }
   ]
}
raja
Published on 23-May-2019 07:54:56
Advertisements