- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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" ] } } }
Advertisements