How to pop a single value in MongoDB?


You can use pop() for this. Let us first create a collection with documents −

> db.persistChangeDemo.insertOne({"Name" : "Larry", "CreditScore": [500,700,760,100]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cdfc52cbf3115999ed51203")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cdfc52cbf3115999ed51203"),
   "Name" : "Larry",
   "CreditScore" : [
      500,
      700,
      760,
      100
   ]
}

Following is the query to pop a value −

> myDocument.CreditScore.pop();
100

Let us save the above document −

> db.persistChangeDemo.save(myDocument);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document once again −

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

This will produce the following output −

{
   "_id" : ObjectId("5cdfc52cbf3115999ed51203"),
   "Name" : "Larry",
   "CreditScore" : [
      500,
      700,
      760
   ]
}

Updated on: 30-Jul-2019

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements