MongoDB query to $pull / $unset with multiple conditions?

MongoDBDatabaseBig Data Analytics

For this, use $pull along with update. Let us create a collection with documents −

> db.demo198.insertOne({"List":{"Values":[10,20,30,30,70,80,90]}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c224503d395bdc21346df")
}
> db.demo198.insertOne({"List":{"Values":[56,978,56,34,23,34]}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c225403d395bdc21346e0")
}
> db.demo198.insertOne({"List":{"Values":[21,12,14,15,34,56]}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3c226603d395bdc21346e1")
}

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

> db.demo198.find();

This will produce the following output −

{ "_id" : ObjectId("5e3c224503d395bdc21346df"), "List" : { "Values" : [ 10, 20, 30, 30, 70, 80, 90 ] } }
{ "_id" : ObjectId("5e3c225403d395bdc21346e0"), "List" : { "Values" : [ 56, 978, 56, 34, 23, 34 ] } }
{ "_id" : ObjectId("5e3c226603d395bdc21346e1"), "List" : { "Values" : [ 21, 12, 14, 15, 34, 56 ] } }

Following is the query to $pull / $unset with multiple conditions −

> db.demo198.update({},{ "$pull": { "List.Values": { "$lt": 40 } } },{ "multi": true });
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

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

> db.demo198.find();

This will produce the following output −

{ "_id" : ObjectId("5e3c224503d395bdc21346df"), "List" : { "Values" : [ 70, 80, 90 ] } }
{ "_id" : ObjectId("5e3c225403d395bdc21346e0"), "List" : { "Values" : [ 56, 978, 56 ] } }
{ "_id" : ObjectId("5e3c226603d395bdc21346e1"), "List" : { "Values" : [ 56 ] } }
raja
Published on 27-Mar-2020 10:06:04
Advertisements