MongoDB-এ স্ট্রিং টাইপের সংখ্যাগুলোর যোগফল বের করতে অ্যাগ্রিগেশন পাইপলাইনে $toInt (বা $toLong, $toDouble) দিয়ে স্ট্রিংকে সংখ্যায় কনভার্ট করে $sum অপারেটর ব্যবহার করা হয়।
নমুনা কালেকশন তৈরি
> db.demo71.insertOne({ "Price": "20" });
{ "acknowledged": true, "insertedId": ObjectId("5e29af210912fae76b13d76e") }
> db.demo71.insertOne({ "Price": "50" });
{ "acknowledged": true, "insertedId": ObjectId("5e29af240912fae76b13d76f") }
> db.demo71.insertOne({ "Price": "20" });
{ "acknowledged": true, "insertedId": ObjectId("5e29af270912fae76b13d770") }
> db.demo71.insertOne({ "Price": "10" });
{ "acknowledged": true, "insertedId": ObjectId("5e29af2d0912fae76b13d771") }
ডকুমেন্টগুলো দেখানো
> db.demo71.find();
আউটপুট:
{ "_id": ObjectId("5e29af210912fae76b13d76e"), "Price": "20" }
{ "_id": ObjectId("5e29af240912fae76b13d76f"), "Price": "50" }
{ "_id": ObjectId("5e29af270912fae76b13d770"), "Price": "20" }
{ "_id": ObjectId("5e29af2d0912fae76b13d771"), "Price": "10" }
স্ট্রিং প্রাইসের যোগফল বের করা
> db.demo71.aggregate([
{
$group: {
_id: null,
TotalPrice: {
$sum: {
$toInt: "$Price"
}
}
}
}
]);
ফলাফল
{ "_id": null, "TotalPrice": 100 }
ব্যাখ্যা:
$toInt: "$Price"- প্রতিটি ডকুমেন্টেরPriceস্ট্রিংকে ইন্টিজারে কনভার্ট করে।$sum- কনভার্ট করা সংখ্যাগুলোর যোগফল করে (২০ + ৫০ + ২০ + ১০ = ১০০)।_id: null- সব ডকুমেন্ট একসাথে গ্রুপ করে।
টাইপ কনভারশন অপারেটরها (MongoDB ৪.০+)
| অপারেটর | কনভারশন | উদাহরণ |
|---|---|---|
$toInt | স্ট্রিং/নাম্বার → ৩২-বিট ইন্টিজার | "42" → 42 |
$toLong | স্ট্রিং/নাম্বার → ৬৪-বিট লং | "42" → Long("42") |
$toDouble | স্ট্রিং/নাম্বার → ডাবল | "3.14" → 3.14 |
$toDecimal | স্ট্রিং/নাম্বার → ডেসিমেল১২৮ | "3.14" → Decimal128("3.14") |
$convert | জেনেরিক কনভারশন (error handling সহ) | { input: "$Price", to: "int", onError: 0 } |
এরর হ্যান্ডলিং (অবৈধ স্ট্রিং থাকলে)
db.demo71.aggregate([
{ $group: {
_id: null,
TotalPrice: {
$sum: {
$convert: {
input: "$Price",
to: "int",
onError: 0,
onNull: 0
}
}
}
}
}
]);
onError এবং onNull দিয়ে কনভারশন ফেল করলে ডিফল্ট ভ্যালু সেট করা যায়।