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

Tạo alias trong truy vấn MongoDB?

Để tạo alias (đặt tên thay thế) cho trường trong kết quả truy vấn MongoDB, bạn sử dụng Aggregation Framework với stage $project.

Tạo dữ liệu mẫu

> db.creatingAliasDemo.insertOne({_id:101,"Name":"John Doe"});
{ "acknowledged" : true, "insertedId" : 101 }
> db.creatingAliasDemo.insertOne({_id:102,"Name":"David Miller"});
{ "acknowledged" : true, "insertedId" : 102 }
> db.creatingAliasDemo.insertOne({_id:103,"Name":"Sam Williams"});
{ "acknowledged" : true, "insertedId" : 103 }

Hiển thị document:

> db.creatingAliasDemo.find().pretty();

Tạo alias "FullName" cho trường "Name"


Kết quả:


Giải thích

  • Trong $project, cú pháp "tênMới": "$tênCũ" tạo alias
  • Dấu $ trước tên trường cũ bắt buộc (tham chiếu đến giá trị trường)
  • Có thể kết hợp nhiều alias, tính toán, chuyển đổi kiểu trong cùng một $project
  • Ví dụ mở rộng: {$project: {_id:1, FullName: "$Name", NameLength: {$strLenCP: "$Name"}}}

Lưu ý: find() không hỗ trợ alias trực tiếp (chỉ include/exclude). Phải dùng aggregation $project hoặc $addFields (MongoDB 3.4+) để đổi tên trường trong kết quả.