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" ] } } }

Updated on: 30-Jul-2019

712 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements