Skip to content
Related Articles

Related Articles

MongoDB – Logical Query Operators
  • Last Updated : 10 May, 2020

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
Recommended Articles
Page :