MongoDB query to pull multiple values from array

MongoDBDatabaseBig Data Analytics

To pull values, use $pull and set multi: true. Let us first create a collection with documents −

> db.demo392.insertOne(
...    {
...       Name: 'Chris',
...       details: [
...          {
...             _id: '101'
...
...          },
...          {
...             _id: '102'
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5d2b3322064be7ab44e802")
}
>
> db.demo392.insertOne(
...    {
...       Name: 'Chris',
...       details: [
...          {
...             _id: '104'
...
...          },
...          {
...             _id: '101'
...          }
...       ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e5d2b3422064be7ab44e803")
}

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

> db.demo392.find();

This will produce the following output −

{
   "_id" : ObjectId("5e5d2b3322064be7ab44e802"), "Name" : "Chris", "details" : [
      { "_id" : "101" }, { "_id" : "102" }
   ]
}
{
   "_id" : ObjectId("5e5d2b3422064be7ab44e803"), "Name" : "Chris", "details" : [
      { "_id" : "104" }, { "_id" : "101" }
   ] 
}

Following is the query to $pull from array −

> db.demo392.update(
...    { },
...    { $pull: { details: { _id: '101' } } },
...    { multi: true }
... )
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

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

> db.demo392.find();

This will produce the following output −

{ "_id" : ObjectId("5e5d2b3322064be7ab44e802"), "Name" : "Chris", "details" : [ { "_id" : "102" } ] }
{ "_id" : ObjectId("5e5d2b3422064be7ab44e803"), "Name" : "Chris", "details" : [ { "_id" : "104" } ] }
raja
Published on 02-Apr-2020 17:45:30
Advertisements