MongoDB  

MongoDB Filter Query Cheat Sheet

Introduction

This article explains how to use filters in MongoDB GUI tools (like MongoDBCompress or Compass) using simple query examples. You’ll learn how to search for records, use conditions, sort results, and filter by dates or partial matches, all without writing any code.

What is a Filter in MongoDB?

A filter is a way to find the exact data you want from a MongoDB collection.

For example,

  • You might want only records where PolicyNo is "123456789"
  • Or records created after a certain date
  • Or records where isSuccess is true

In MongoDB GUI tools, you write filters using a JSON format (such as { "key": "value" }).

Common Filter Queries

1. Match Exact Value

{ "PolicyNo": "123456789" }

Finds records where PolicyNo is exactly 123456789.

2. Not Equal To

{ "AppointmentID": { "$ne": 0 } }

Finds records where AppointmentID is not 0.

3. Greater Than / Less Than

{ "LeadID": { "$gt": 10000000 } }
  • $gt = greater than
  • $lt = less than
  • $gte = greater than or equal
  • $lte = less than or equal

4. Multiple Values (IN)

{ "LogTypeID": { "$in": [1, 2] } }

Finds records where LogTypeID is either 1 or 2.

5. AND Condition

{
  "PolicyNo": "123456789",
  "isSuccess": true
}

Finds records where both conditions are true.

6. OR Condition

{
  "$or": [
    { "isSuccess": true },
    { "LogTypeID": 2 }
  ]
}

Finds records where either condition is true.

7. Field Exists or Not

{ "Message": { "$exists": false } }

Finds records where the Message field does not exist.

8. Partial Match with Regex

{ "LogName": { "$regex": "Benefit" } }

Finds records where LogName contains the word "Benefit".

Starts with,

{ "LogName": { "$regex": "^Get" } }

Ends with,

{ "LogName": { "$regex": "BAL$" } }

9. Date Range Filter

{
  "CreatedOn": {
    "$gte": { "$date": "2024-09-01T00:00:00Z" },
    "$lte": { "$date": "2024-09-30T23:59:59Z" }
  }
}

Shows records created between September 1 and September 30, 2024.

This works only if CreatedOn is stored as a Date, not as a string.

Sorting Results

Newest First (Recommended)

{ "_id": -1 }

Oldest First

{ "_id": 1 }

Pro Tips

  • Always wrap your filter in { }
  • For an exact match, just use the key and value
  • Use $ne, $in, $gt, etc., for smart filtering
  • Use _id for sorting if CreatedOn is not a Date

Conclusion

If you are using MongoDB Compress or MongoDB Compass, this cheat sheet can help you quickly find the right data by simply pasting the filters into the GUI. No coding needed!

Whether you're debugging logs, checking policy records, or analyzing errors, filters save time and help you focus only on what matters.

Happy Coding !!