How to convert string to numerical values in MongoDB?


You need to use some code in order to convert a string to numerical values in MongoDB.

Let us first create a collection with a document. The query to create a collection with a document is as follows:

> db.convertStringToNumberDemo.insertOne({"EmployeeId":"101","EmployeeName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f56528d10a061296a3c31")
}
> db.convertStringToNumberDemo.insertOne({"EmployeeId":"1120","EmployeeName":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f56648d10a061296a3c32")
}
> db.convertStringToNumberDemo.insertOne({"EmployeeId":"3210","EmployeeName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7f566e8d10a061296a3c33")
}

Display all documents from the collection with the help of find() method. The query is as follows −

> db.convertStringToNumberDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c7f56528d10a061296a3c31"),
   "EmployeeId" : "101",
   "EmployeeName" : "Larry"
}
{
   "_id" : ObjectId("5c7f56648d10a061296a3c32"),
   "EmployeeId" : "1120",
   "EmployeeName" : "Mike"
}
{
   "_id" : ObjectId("5c7f566e8d10a061296a3c33"),
   "EmployeeId" : "3210",
   "EmployeeName" : "Sam"
}

Here is the query to convert a string to numerical values in MongoDB. Change “EmployeeId” string to numerical values. The query is as follows −

> db.convertStringToNumberDemo.find().forEach(function(x)
   ... {
      ... db.convertStringToNumberDemo.update
      ... (
         ...
         ... {
            ... "_id": x._id,
            ...
         ... },
         ... {
            ... "$set":
            ... {
               ... "EmployeeId": parseInt(x.EmployeeId)
            ... }
         ... }
      ... )
   ... }
... );

Now check the documents from the collection. The query is as follows −

> db.convertStringToNumberDemo.find().pretty();

The following is the output displaying the string values (EmployeeId) converted to an integer −

{
   "_id" : ObjectId("5c7f56528d10a061296a3c31"),
   "EmployeeId" : 101,
   "EmployeeName" : "Larry"
}
{
   "_id" : ObjectId("5c7f56648d10a061296a3c32"),
   "EmployeeId" : 1120,
   "EmployeeName" : "Mike"
}
{
   "_id" : ObjectId("5c7f566e8d10a061296a3c33"),
   "EmployeeId" : 3210,
   "EmployeeName" : "Sam"
}

Updated on: 30-Jul-2019

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements