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" ] } } }
raja
Published on 14-Jun-2019 15:19:20
Advertisements