0
0
MongodbConceptBeginner · 3 min read

MinKey and MaxKey in MongoDB: What They Are and How to Use

In MongoDB, MinKey and MaxKey are special data types used to compare values in queries and sorting. MinKey is considered lower than all other values, and MaxKey is higher than all other values, helping define range boundaries or sort extremes.
⚙️

How It Works

Imagine you have a list of items sorted from smallest to largest. Sometimes, you want to mark the absolute start or end of that list, even if you don't know the exact smallest or largest value. In MongoDB, MinKey acts like the smallest possible value, always less than any other data. Similarly, MaxKey acts like the largest possible value, always greater than any other data.

This helps MongoDB when it needs to compare values during queries or sorting. For example, if you want to find all documents with a key greater than a certain value but less than the maximum possible, you can use MaxKey to represent that upper limit. These types are especially useful in range queries and index boundaries.

💻

Example

This example shows how to use MinKey and MaxKey in a query to find documents within a range.
javascript
db.collection.insertMany([
  { _id: 1, score: 10 },
  { _id: 2, score: 20 },
  { _id: 3, score: 30 }
])

// Find documents with score greater than MinKey and less than MaxKey
const minKey = new MinKey();
const maxKey = new MaxKey();

const results = db.collection.find({
  score: { $gt: minKey, $lt: maxKey }
}).toArray()

printjson(results)
Output
[ { "_id" : 1, "score" : 10 }, { "_id" : 2, "score" : 20 }, { "_id" : 3, "score" : 30 } ]
🎯

When to Use

Use MinKey and MaxKey when you need to define open-ended ranges in queries or when setting index bounds. For example, if you want to query all documents with a field value greater than any possible minimum or less than any possible maximum, these types help express that clearly.

They are also useful in sorting operations where you want to ensure a value appears at the very start or end of a sorted list regardless of other data. This can help in pagination, range scans, or when working with complex query filters.

Key Points

  • MinKey is less than all other BSON types.
  • MaxKey is greater than all other BSON types.
  • They help define range boundaries in queries and indexes.
  • Useful for sorting extremes and open-ended queries.

Key Takeaways

MinKey and MaxKey represent the lowest and highest possible BSON values in MongoDB.
They are used to create open-ended range queries and set index bounds.
MinKey is always less than any other value; MaxKey is always greater.
Use them to control sorting order and query ranges effectively.