Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Chuyển đổi giá trị thành String trong MongoDB với $toString

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
$toStringBất kỳString
$toInt / $toLongString, Double, DecimalInt32 / Int64
$toDoubleString, Int, Long, DecimalDouble
$toDecimalString, Int, Long, DoubleDecimal128
$toBoolBất kỳBoolean
$toDateString (ISODate), Long (epoch ms), ObjectIdDate
$toObjectIdString (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 $convert với onError/onNull để xử lý an toàn.
  • $toString trên ObjectId trả về chuỗi 24 ký tự hex (không có ObjectId("...")).