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 $in operator 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).

Updated on: 2026-03-15T01:31:38+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements