Comparison Operators
When you're working with different data types or comparing complex structures, comparison operators become your toolkit. They help you compare values across different types and structures in your documents.
These operators go beyond simple value comparisons. They let you compare embedded documents, arrays, and even handle those tricky NULL values that always seem to cause problems.
Comparing Different Data Types
MongoDB has rules about comparing different types. When you compare a number with a string, MongoDB follows specific comparison rules. For example, comparing a number with a string will work in some cases, but it's generally better to keep your data types consistent.
The comparison order is: MinValue < Null < Numbers < Symbol < String < Object < Array < BinaryData < ObjectId < Boolean < Date < Timestamp < RegularExpression
db.data.find({ value: { $eq: "100" } })
db.data.find({ value: { $eq: 100 } })
db.data.find({ value: { $gt: "abc" } })
Try it Yourself →
Comparing Embedded Documents
When comparing embedded documents, MongoDB compares the fields in the specified order. This means { a: 1, b: 2 } is not equal to { b: 2, a: 1 } because the order matters.
You can also compare individual fields within an embedded document using dot notation. This gives you fine-grained control over what you're comparing.
db.inventory.find({ size: { h: 14, w: 21, unit: "cm" } })
db.inventory.find({ "size.w": { $gt: 10 } })
db.users.find({ "address.zipcode": { $eq: "10001" } })
Try it Yourself →
Comparing Arrays
Array comparisons in MongoDB are interesting. When comparing arrays, MongoDB compares elements in the arrays in order. Two arrays are equal if they have the same elements in the same order.
You can also compare individual elements within arrays. This is useful when you want to check if a specific position in an array matches a value.
db.products.find({ tags: ["red", "large"] })
db.products.find({ "tags.0": "red" })
db.users.find({ scores: { $gt: 80, $lt: 90 } })
Try it Yourself →