MongoDB query to convert string to int?



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

> db.demo369.insertOne({"Price":"1000000"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e57e2e32ae06a1609a00aed") } > db.demo369.insertOne({"Price":"1747864"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e57e2e92ae06a1609a00aee") } > db.demo369.insertOne({"Price":"19548575"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e57e2ee2ae06a1609a00aef") }

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

> db.demo369.find();

This will produce the following output −

{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : "1000000" } { "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : "1747864" } { "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : "19548575" }

Following is the query to convert string to int −

> db.demo369.find().forEach( function (d) { ...    d.Price= parseInt(d.Price); ...    db.demo369.save(d); ... });

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

> db.demo369.find();

This will produce the following output −

{ "_id" : ObjectId("5e57e2e32ae06a1609a00aed"), "Price" : 1000000 } { "_id" : ObjectId("5e57e2e92ae06a1609a00aee"), "Price" : 1747864 } { "_id" : ObjectId("5e57e2ee2ae06a1609a00aef"), "Price" : 19548575 }
Updated on: 2020-04-02T12:50:17+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements