Remove object from array in MongoDB?

MongoDBDatabaseBig Data Analytics

To remove object from an array in MongoDB, you can use $pull operator. The syntax is as follows:

db.yourCollectionName.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}},
false,true);

To understand the above syntax, let us create a collection with document. The query to create a collection with document is as follows:

> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23,
... "CustomerDetails":[
... {
... "CustomerId":100,
... "CustomerProduct":"Product-1"
... },
... {
... "CustomerId":150,
... "CustomerProduct":"Product-2"
... },
... {
... "CustomerId":200,
... "CustomerProduct":"Product-3"
... }
... ]
... });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ea036a0c51185aefbd14f")
}

Display all documents from a collection with the help of find() method. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 150,
         "CustomerProduct" : "Product-2"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}

Here is the query to remove object from an array in MongoDB:

> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
... {$pull:{"CustomerDetails":{"CustomerId":150}}},
... false,true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Above, we have removed object from an array. Let us display document from the collection. The query is as follows:

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

The following is the output:

{
   "_id" : ObjectId("5c6ea036a0c51185aefbd14f"),
   "CustomerName" : "Maxwell",
   "CustomerAge" : 23,
   "CustomerDetails" : [
      {
         "CustomerId" : 100,
         "CustomerProduct" : "Product-1"
      },
      {
         "CustomerId" : 200,
         "CustomerProduct" : "Product-3"
      }
   ]
}
raja
Published on 18-Mar-2019 16:25:36
Advertisements