SQL where clause equivalents MongoDB

How to perform SQL where clause equivalents in MongoDB

Comparison query operators provides a way to perform SQL where clause equivalents in MongoDB. This tutorial explains you on how to perform query on specific operators, including syntax and examples.

Let us insert the following documents in a collection called “posts” before we run the following examples.

1. Equality: $eq ( = operator in SQL WHERE Clause)

$eq comparison query operator is used to match values that are equal to a specified value. Below is the syntax and example.

Example:

> db.posts.find({ “by_user”: { $eq: “sneppets” } }).pretty()

2. Less Than: $lt (< operator in SQL WHERE Clause)

$lt comparison query operator is used to match values that are less than a specified value. Below is the syntax and example.

Example:

> db.posts.find({ “likes”: { $lt: 30 } }).pretty()

3. Less Than Equals: $lte (<= operator in SQL WHERE Clause)

$lte comparison query operator is used to match values that are less than or equal to a specified value. Below is the syntax and example.

Example:

> db.posts.find({ “likes”: { $lte: 30 } }).pretty()

4. Greater Than: $gt (> operator in SQL WHERE Clause)

$gt comparison query operator is used to match values that greater than a specified value. Below is the syntax and example.

Example:

> db.posts.find({ “likes”: { $gt: 30 } }).pretty()

5. Greater Than Equals: $gte (>= operator in SQL WHERE Clause)

$gte comparison query operator is used to match values that greater than or equal to a specified value. Below is the syntax and example.

Example:

> db.posts.find({ “likes”: { $gte: 50 } }).pretty()

6. Not Equals: $ne (<> operator in SQL WHERE Clause)

$ne comparison query operator is used to match values that are not equal to a specified value. Below is the syntax and example.

Example:

> db.posts.find({ “by_user”: { $ne: “mongodb” } }).pretty()

7. In: $in ( IN operator in SQL WHERE Clause)

$in comparison query operator is used to match any of the values that are specified in an array. Below is the syntax and example.

Example:

> db.posts.find({ “by_user”: { $in: [“sneppets”,”sneppet”,”google”] } }).pretty()

8. Not In: $nin (NOT IN operator in SQL WHERE Clause)

$nin comparison query operator matches none of the values specified in an array. Below is the syntax and example.

Example:

> db.posts.find({ “by_user”: { $nin: [“mongodb”,”google”] } }).pretty()

Further Learning

References

Leave a Reply

avatar
  Subscribe  
Notify of