Syntax error Can we use NOT and AND together in MongoDB?

Can we use NOT and AND together in MongoDB?



Yes, we can use the NOT and AND together in MongoDB. The syntax is as follows

NOT X AND NOT Y = NOT (X AND Y)
Let us see the working of above syntax.
If both X and Y will be true then last result will be false.
If one of the operands gives result false then last result will be true.

Following is the query to create a collection with documents

> db.NotAndDemo.insertOne({"StudentName":"John","StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c98746a330fd0aa0d2fe4a8")
}
> db.NotAndDemo.insertOne({"StudentName":"John","StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c987478330fd0aa0d2fe4a9")
}
> db.NotAndDemo.insertOne({"StudentName":"David","StudentCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c987487330fd0aa0d2fe4aa")
}
> db.NotAndDemo.insertOne({"StudentName":"Chris","StudentCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9874ac330fd0aa0d2fe4ab")
}
> db.NotAndDemo.insertOne({"StudentName":"Chris","StudentCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9874b7330fd0aa0d2fe4ac")
}

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

> db.NotAndDemo.find().pretty();
This will produce the following output:
{
   "_id" : ObjectId("5c98746a330fd0aa0d2fe4a8"),
   "StudentName" : "John",
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5c987478330fd0aa0d2fe4a9"),
   "StudentName" : "John",
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5c987487330fd0aa0d2fe4aa"),
   "StudentName" : "David",
   "StudentCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9874ac330fd0aa0d2fe4ab"),
   "StudentName" : "Chris",
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5c9874b7330fd0aa0d2fe4ac"),
   "StudentName" : "Chris",
   "StudentCountryName" : "US"
}

Following is the query to use NOT and AND together, which is the same as NOT X OR NOT Y for NOT (X AND Y)

> db.NotAndDemo.find({
...    "$or": [
...       {"StudentName": {"$ne": "Chris"}},
...       {"StudentCountryName": {"$ne": "US"}}
...    ]
... }).pretty();

This will produce the following output

{
   "_id" : ObjectId("5c98746a330fd0aa0d2fe4a8"),
   "StudentName" : "John",
   "StudentCountryName" : "US"
}
{
   "_id" : ObjectId("5c987478330fd0aa0d2fe4a9"),
   "StudentName" : "John",
   "StudentCountryName" : "UK"
}
{
   "_id" : ObjectId("5c987487330fd0aa0d2fe4aa"),
   "StudentName" : "David",
   "StudentCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c9874ac330fd0aa0d2fe4ab"),
   "StudentName" : "Chris",
   "StudentCountryName" : "UK"
}
Updated on: 2019-07-30T22:30:25+05:30

241 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements