Syntax error MongoDB query to convert numeric string to number

MongoDB query to convert numeric string to number



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 }
Updated on: 2020-03-27T10:51:41+05:30

622 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements