Computer >> Computer tutorials >  >> Programming >> MongoDB

How do I remove elements not matching conditions in MongoDB?


To remove elements, use $pull and for such conditions, use $ne. The $ne in MongoDB is used to select the documents where the value of the field is not equal to the specified value.

Let us create a collection with documents −

> db.demo410.insertOne(
...    {
...       details: [{isMarried:false}, {isMarried:true}, {isMarried:false}, {isMarried:"Chris"}]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e70efc515dc524f70227681")
}

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

> db.demo410.find();

This will produce the following output −

{ "_id" : ObjectId("5e70efc515dc524f70227681"), "details" : [ { "isMarried" : false }, { "isMarried" : true }, { "isMarried" : false }, { "isMarried" : "Chris" } ] }

Following is the query to remove elements not matching conditions in MongoDB −

> db.demo410.updateMany(
...    { "details": { "$elemMatch": { "isMarried": { "$ne": true } } } },
...    { "$pull": { "details": { "isMarried": { "$ne": true } } } }
... )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

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

> db.demo410.find();

This will produce the following output −

{ "_id" : ObjectId("5e70efc515dc524f70227681"), "details" : [ { "isMarried" : true } ] }