Toán tử $toString (có từ MongoDB 4.0) cho phép chuyển đổi các kiểu dữ liệu (ObjectId, Number, Date, Boolean...) thành chuỗi (string) trong Aggregation Pipeline.
Cú pháp
{ $toString: "" }
Ví dụ: Chuyển ObjectId thành String
Tạo collection objectidToStringDemo:
> db.objectidToStringDemo.insertOne({ "UserName": "John" });
> db.objectidToStringDemo.insertOne({ "UserName": "Chris" });
> db.objectidToStringDemo.insertOne({ "UserName": "Larry" });
> db.objectidToStringDemo.insertOne({ "UserName": "Robert" });
Hiển thị (ObjectId gốc):
> db.objectidToStringDemo.find().pretty();
Kết quả:
{ "_id" : ObjectId("5c92b80036de59bd9de0639d"), "UserName" : "John" }
{ "_id" : ObjectId("5c92b80436de59bd9de0639e"), "UserName" : "Chris" }
{ "_id" : ObjectId("5c92b80936de59bd9de0639f"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c92b81836de59bd9de063a0"), "UserName" : "Robert" }
Aggregation với $toString
> db.objectidToStringDemo.aggregate([
{ $project: { _id: { $toString: "$_id" } } }
]);
Kết quả (ObjectId đã thành string):
{ "_id" : "5c92b80036de59bd9de0639d" }
{ "_id" : "5c92b80436de59bd9de0639e" }
{ "_id" : "5c92b80936de59bd9de0639f" }
{ "_id" : "5c92b81836de59bd9de063a0" }
Chuyển ngược: String → ObjectId với $toObjectId
> db.objectidToStringDemo.aggregate([
{ $project: { _id: { $toObjectId: "$_id" } } }
]);
Kết quả: Trở lại kiểu ObjectId.
Các chuyển đổi phổ biến khác
| Toán tử | Chuyển từ | Chuyển thành |
|---|---|---|
$toString | Bất kỳ | String |
$toInt / $toLong | String, Double, Decimal | Int32 / Int64 |
$toDouble | String, Int, Long, Decimal | Double |
$toDecimal | String, Int, Long, Double | Decimal128 |
$toBool | Bất kỳ | Boolean |
$toDate | String (ISODate), Long (epoch ms), ObjectId | Date |
$toObjectId | String (24 hex chars) | ObjectId |
Lưu ý
- Nếu chuyển đổi thất bại (ví dụ: string "abc" sang int), aggregation sẽ báo lỗi. Dùng
$convertvớionError/onNullđể xử lý an toàn. $toStringtrên ObjectId trả về chuỗi 24 ký tự hex (không cóObjectId("...")).