Invert Result of MongoDB Query (Implement Opposite of $and operation)?

MongoDBDatabaseBig Data Analytics

To invert result i.e. opposite of $and operation, use $OR along with $ne. Let us first create a collection with documents −

> db.demo4.insert({uid:1,"Name":"Chris","Age":22});
WriteResult({ "nInserted" : 1 })
> db.demo4.insert({uid:2,"Name":"David","Age":21});
WriteResult({ "nInserted" : 1 })
> db.demo4.insert({uid:3,"Name":"Bob","Age":23});
WriteResult({ "nInserted" : 1 })
> db.demo4.insert({uid:1,"Name":"Carol","Age":20});
WriteResult({ "nInserted" : 1 })

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

> db.demo4.find();

This will produce the following output −

{ "_id" : ObjectId("5e0a1da125ddae1f53b62221"), "uid" : 1, "Name" : "Chris", "Age" : 22 }
{ "_id" : ObjectId("5e0a1db025ddae1f53b62222"), "uid" : 2, "Name" : "David", "Age" : 21 }
{ "_id" : ObjectId("5e0a1dc225ddae1f53b62223"), "uid" : 3, "Name" : "Bob", "Age" : 23 }
{ "_id" : ObjectId("5e0a1dd225ddae1f53b62224"), "uid" : 1, "Name" : "Carol", "Age" : 20 }

Here is the query to get invert result −

> db.demo4.find({uid:2,$or: [{"Name": {$ne: "Carol"}}, {"Age": {$ne: 21}}]});

This will produce the following output −

{ "_id" : ObjectId("5e0a1db025ddae1f53b62222"), "uid" : 2, "Name" : "David", "Age" : 21 }
raja
Published on 31-Mar-2020 08:33:28
Advertisements