MongoDB – Logical Query Operators

MongoDB supports logical query operators. These operators are used for filtering the data and getting precise results based on the given conditions. The following table contains the comparison query operators:

Operator Description
$and It is used to join query clauses with a logical AND and return all documents that match the given conditions of both clauses.
$or It is used to join query clauses with a logical OR and return all documents that match the given conditions of either clause.
$not It is used to invert the effect of the query expressions and return documents that does not match the query expression.
$nor It is used to join query clauses with a logical NOR and return all documents that fail to match both clauses.

In the following examples, we are working with:

Database: GeeksforGeeks
Collection: contributor
Document: three documents that contain the details of the contributors in the form of field-value pairs.

Matching values using $and operator:

In this example, we are retrieving only those employee’s documents whose branch is CSE and joiningYear is 2018.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({$and: [{branch: "CSE"}, {joiningYear: 2018}]}).pretty()

chevron_right




Matching values using $nor operator:

In this example, we are retrieving only those employee’s documents whose salary is not 3000 and whose branch is not ECE.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({$nor: [{salary: 3000}, {branch: "ECE"}]}).pretty()

chevron_right


Matching values using $or operator:

In this example, we are retrieving only those employee’s documents whose branch is ECE or joiningYear is 2017.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({$or: [{branch: "ECE"}, {joiningYear: 2017}]}).pretty()

chevron_right


Matching values using $not operator:

In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty()

chevron_right





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.