MongoDB query to convert numeric string to number

MongoDBDatabaseBig Data Analytics

To convert numeric string to number, use parseInt() in MongoDB. Let us create a collection with documents −

> db.demo208.insertOne( { "value":"50"} );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d92d803d395bdc21346f6")
}
> db.demo208.insertOne( { "value":"2350"} );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3d92dd03d395bdc21346f7")
}

Display all documents from a collection with the help of find() method −

> db.demo208.find();

This will produce the following output −

{ "_id" : ObjectId("5e3d92d803d395bdc21346f6"), "value" : "50" }
{ "_id" : ObjectId("5e3d92dd03d395bdc21346f7"), "value" : "2350" }

Following is the query to convert numeric string to number −

> db.demo208.find().forEach( function (doc) {
...   doc.value = parseInt(doc.value);
...   db.demo208.save(doc);
...});

Display all documents from a collection with the help of find() method −

> db.demo208.find();

This will produce the following output −

{ "_id" : ObjectId("5e3d92d803d395bdc21346f6"), "value" : 50 }
{ "_id" : ObjectId("5e3d92dd03d395bdc21346f7"), "value" : 2350 }
raja
Published on 27-Mar-2020 10:50:39
Advertisements