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
How to search for string or number in a field with MongoDB?
To search for string or number values in a field with MongoDB, use the $in operator with an array containing both the string and numeric versions of the value you want to match.
Syntax
db.collection.find({
"fieldName": { $in: ["stringValue", numericValue] }
});
Sample Data
Let us create a collection with documents containing both string and numeric values ?
db.searchForStringOrNumberDemo.insertMany([
{
"StudentName": "Larry",
"StudentDetails": {
"StudentMarks": {
"StudentMongoDBMarks": [44]
}
}
},
{
"StudentName": "Larry",
"StudentDetails": {
"StudentMarks": {
"StudentMongoDBMarks": ["44"]
}
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ce2407c36e8b255a5eee944"),
ObjectId("5ce240f036e8b255a5eee945")
]
}
View Sample Data
db.searchForStringOrNumberDemo.find().pretty();
{
"_id": ObjectId("5ce2407c36e8b255a5eee944"),
"StudentName": "Larry",
"StudentDetails": {
"StudentMarks": {
"StudentMongoDBMarks": [44]
}
}
}
{
"_id": ObjectId("5ce240f036e8b255a5eee945"),
"StudentName": "Larry",
"StudentDetails": {
"StudentMarks": {
"StudentMongoDBMarks": ["44"]
}
}
}
Search for String or Number
Use $in with both string and numeric values to match either data type ?
db.searchForStringOrNumberDemo.find({
"StudentDetails.StudentMarks.StudentMongoDBMarks": {
$in: ["44", 44]
}
});
{
"_id": ObjectId("5ce2407c36e8b255a5eee944"),
"StudentName": "Larry",
"StudentDetails": {
"StudentMarks": {
"StudentMongoDBMarks": [44]
}
}
}
{
"_id": ObjectId("5ce240f036e8b255a5eee945"),
"StudentName": "Larry",
"StudentDetails": {
"StudentMarks": {
"StudentMongoDBMarks": ["44"]
}
}
}
Key Points
- The
$inoperator matches any value in the provided array - Include both string and numeric versions to handle type variations
- Works with nested fields using dot notation
Conclusion
Use the $in operator with an array containing both string and numeric versions of your target value. This ensures you match documents regardless of how the data was stored (as string or number).
Advertisements
