Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
MongoDB query to convert a string with commas to double
For such conversion, use aggregate(). Let us create a collection with documents −
> db.demo335.insertOne({"Value":"45,67,78.0"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522a1cf8647eb59e562091")
}
> db.demo335.insertOne({"Value":"17664,76,534.0"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522a26f8647eb59e562092")
}
> db.demo335.insertOne({"Value":"8899,322,135,875.50"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522a34f8647eb59e562093")
}
> db.demo335.insertOne({"Value":"1,533.07"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e522ab9f8647eb59e562094")
}
Display all documents from a collection with the help of find() method −
> db.demo335.find();
This will produce the following output −
{ "_id" : ObjectId("5e522a1cf8647eb59e562091"), "Value" : "45,67,78.0" }
{ "_id" : ObjectId("5e522a26f8647eb59e562092"), "Value" : "17664,76,534.0" }
{ "_id" : ObjectId("5e522a34f8647eb59e562093"), "Value" : "8899,322,135,875.50" }
{ "_id" : ObjectId("5e522ab9f8647eb59e562094"), "Value" : "1,533.07" }
Following is the query to convert a string with commas to double −
db.demo335.aggregate([
... { $project: {
... data: {
... $convert: {
... input: {
... $reduce: {
... input: {
... $split: ['$Value', ',']
... },
... initialValue: '',
... in: {
... $concat: ['$$value', '$$this']
... }
... }
... },
... to: 'double',
... onError: 0
... }
... }
... }}
... ])
This will produce the following output −
{ "_id" : ObjectId("5e522a1cf8647eb59e562091"), "data" : 456778 }
{ "_id" : ObjectId("5e522a26f8647eb59e562092"), "data" : 1766476534 }
{ "_id" : ObjectId("5e522a34f8647eb59e562093"), "data" : 8899322135875.5 }
{ "_id" : ObjectId("5e522ab9f8647eb59e562094"), "data" : 1533.07 } Advertisements
