MongoDB में स्ट्रिंग से संख्या रूपांतरण: कॉमा हटाकर डबल बनाना
संख्याओं को दर्शाने वाली स्ट्रिंग्स जिनमें कॉमा विभाजक हों (उदाहरण: "1,533.07"), को संख्यात्मक प्रकार में बदलने के लिए एग्रीगेशन पाइपलाइन में $split, $reduce/$concat, और $convert का संयोजन उपयोग करें।
नमूना डेटा
> 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") }
एग्रीगेशन पाइपलाइन
db.demo335.aggregate([
{$project: {
data: {
$convert: {
input: {
$reduce: {
input: {$split: ["$Value", ","]},
initialValue: "",
in: {$concat: ["$$value", "$$this"]}
}
},
to: "double",
onError: 0
}
}
}}
]);
परिणाम
{ "data": 456778 }
{ "data": 1766476534 }
{ "data": 8899322135875.5 }
{ "data": 1533.07 }
पाइपलाइन: 1) $split कॉमा द्वारा विभाजित करता है, 2) $reduce + $concat भागों को जोड़ता है, 3) $convert परिणाम को double में बदलता है। onError: 0 अमान्य इनपुट के लिए डिफ़ॉल्ट प्रदान करता है।