MongoDB 查询将带有逗号的字符串转换为双精度
对于此类转换,使用 aggregate()。我们创建一个包含以下文档的集合 -
> 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") }
使用 find() 方法显示集合中的所有文档 -
> db.demo335.find();
这将产生以下输出 -
{ "_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" }
以下是将带有逗号的字符串转换为双精度的查询 -
db.demo335.aggregate([ ... { $project: { ... data: { ... $convert: { ... input: { ... $reduce: { ... input: { ... $split: ['$Value', ','] ... }, ... initialValue: '', ... in: { ... $concat: ['$$value', '$$this'] ... } ... } ... }, ... to: 'double', ... onError: 0 ... } ... } ... }} ... ])
这将产生以下输出 -
{ "_id" : ObjectId("5e522a1cf8647eb59e562091"), "data" : 456778 } { "_id" : ObjectId("5e522a26f8647eb59e562092"), "data" : 1766476534 } { "_id" : ObjectId("5e522a34f8647eb59e562093"), "data" : 8899322135875.5 } { "_id" : ObjectId("5e522ab9f8647eb59e562094"), "data" : 1533.07 }
广告