Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query for exact match
For exact match queries in MongoDB, you can combine the $exists operator with field conditions to ensure precise matching, especially when dealing with fields that could contain either single values or arrays.
Syntax
db.collection.find({
$and: [
{"field.0": {$exists: false}},
{"field": "exactValue"}
]
});
Sample Data
db.demo290.insertMany([
{"ListOfName": "Chris"},
{"ListOfName": ["Chris", "David"]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4c0c9e5d93261e4bc9ea2d"),
ObjectId("5e4c0cb05d93261e4bc9ea2e")
]
}
Display all documents from the collection ?
db.demo290.find();
{ "_id": ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName": "Chris" }
{ "_id": ObjectId("5e4c0cb05d93261e4bc9ea2e"), "ListOfName": ["Chris", "David"] }
Example: Exact Match Query
Find documents where ListOfName is exactly the string "Chris" (not an array containing "Chris") ?
db.demo290.find({
$and: [
{"ListOfName.0": {$exists: false}},
{"ListOfName": "Chris"}
]
});
{ "_id": ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName": "Chris" }
How It Works
-
{"ListOfName.0": {$exists: false}}ensures the field is NOT an array (arrays have index 0) -
{"ListOfName": "Chris"}matches the exact string value -
$andcombines both conditions for precise filtering
Conclusion
Use $exists: false with array index notation to distinguish between string values and arrays. This approach ensures exact field type and value matching in MongoDB queries.
Advertisements
