

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to search for string or number in a field with MongoDB?
You can use $in operator for this. Let us first create a collection with documents −
> db.searchForStringOrNumberDemo.insertOne( { "_id": new ObjectId(), "StudentName": "Larry", "StudentDetails": { "StudentMarks": { "StudentMongoDBMarks": [44] } } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce2407c36e8b255a5eee944") } > db.searchForStringOrNumberDemo.insertOne( { "_id": new ObjectId(), "StudentName": "Larry", "StudentDetails": { "StudentMarks": { "StudentMongoDBMarks": ["44"] } } } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce240f036e8b255a5eee945") }
Following is the query to display all documents from a collection with the help of find() method −
> db.searchForStringOrNumberDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ce2407c36e8b255a5eee944"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ 44 ] } } } { "_id" : ObjectId("5ce240f036e8b255a5eee945"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ "44" ] } } }
Following is the query to search for string or number in a field −
>db.searchForStringOrNumberDemo.find({"StudentDetails.StudentMarks.StudentMongoDBMarks": { "$in": ["44",44] } });
This will produce the following output −
{ "_id" : ObjectId("5ce2407c36e8b255a5eee944"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ 44 ] } } } { "_id" : ObjectId("5ce240f036e8b255a5eee945"), "StudentName" : "Larry", "StudentDetails" : { "StudentMarks" : { "StudentMongoDBMarks" : [ "44" ] } } }
- Related Questions & Answers
- How to search for a record (field) and then delete it in MongoDB?
- Search a sub-field on MongoDB?
- MongoDB query to search for string like “@email” in the field values
- Search by specific field in MongoDB
- How to search for a date in MySQL timestamp field?
- Limit number of values in a field with MongoDB?
- How to search for a string in JavaScript?
- Search a string with special characters in a MongoDB document?
- How to check if a field in MongoDB is [] or {}?
- Search a value in an object with number keys with MongoDB
- How to check if field is a number in MongoDB?
- Query MongoDB for a nested search
- MongoDB query for a single field
- How to search for a pattern in a Java string?
- How to search a string for a pattern in JavaScript?
Advertisements