Chuyển đổi (Cast) String thành ObjectId với Aggregation
Khi _id lưu dưới dạng string, dùng aggregation $toObjectId (MongoDB 4.0+) hoặc $convert để chuyển thành ObjectId thật.
1. Dữ liệu: _id là string
> db.demo460.insertOne({ "_id": "5ab9cbfa31c2ab715d42129e" });
{ "acknowledged": true, "insertedId": "5ab9cbfa31c2ab715d42129e" }
2. Xem dữ liệu
> db.demo460.find();
{ "_id": "5ab9cbfa31c2ab715d42129e" }
3. Chuyển đổi với $convert (MongoDB 4.0+)
> db.demo460.aggregate([
{
$addFields: {
objectIdValue: { $toObjectId: "$_id" }
// Hoặc dùng $convert đầy đủ:
// objectIdValue: { $convert: { input: "$_id", to: "objectId" } }
}
}
]);
4. Kết quả
{
"_id": "5ab9cbfa31c2ab715d42129e",
"objectIdValue": ObjectId("5ab9cbfa31c2ab715d42129e")
}
Các hàm chuyển đổi kiểu dữ liệu (MongoDB 4.0+)
| Rút gọn | Đầy đủ ($convert) | Chuyển sang |
|---|---|---|
| $toObjectId | { $convert: { input: ..., to: "objectId" } } | ObjectId |
| $toString | { $convert: { input: ..., to: "string" } } | String |
| $toInt / $toLong | { $convert: { input: ..., to: "int" / "long" } } | Int32 / Int64 |
| $toDouble | { $convert: { input: ..., to: "double" } } | Double |
| $toDate | { $convert: { input: ..., to: "date" } } | Date |
| $toBool | { $convert: { input: ..., to: "bool" } } | Boolean |
Xử lý lỗi chuyển đổi (onError, onNull)
db.demo460.aggregate([
{
$addFields: {
safeObjectId: {
$convert: {
input: "$_id",
to: "objectId",
onError: null, // Trả về null nếu lỗi format
onNull: null // Trả về null nếu input null
}
}
}
}
]);
Trong application (Node.js driver)
const { ObjectId } = require('mongodb');
const id = new ObjectId("5ab9cbfa31c2ab715d42129e"); // Tự động validate