Trong MongoDB Shell (mongosh/legacy mongo shell), bạn có thể lưu tên collection vào biến JavaScript để tái sử dụng, tránh gõ lặp lại.
Cú pháp
var tenBien = "tênCollection"; db[tenBien].phươngThức();
Ví dụ minh họa
Gán tên collection vào biến storeCollectionName:
> var storeCollectionName = "new_Collection";
> db[storeCollectionName].insertOne({"UserName": "John", "UserAge": 21});
> db[storeCollectionName].insertOne({"UserName": "Carol", "UserAge": 24});
> db[storeCollectionName].insertOne({"UserName": "Mike", "UserAge": 27});
Truy vấn dữ liệu:
> db[storeCollectionName].find().pretty();
Kết quả:
{ "_id" : ObjectId("..."), "UserName" : "John", "UserAge" : 21 }
{ "_id" : ObjectId("..."), "UserName" : "Carol", "UserAge" : 24 }
{ "_id" : ObjectId("..."), "UserName" : "Mike", "UserAge" : 27 }
Lưu ý quan trọng
- Cách này chỉ hoạt động trong MongoDB Shell (môi trường JavaScript).
- Trong driver ngôn ngữ lập trình (Node.js, Python, Java...), bạn truy xuất collection động bằng cú pháp:
db.collection(tênBiến)(Node.js) hoặcdb[tênBiến](Python PyMongo). - Tên biến phải tuân theo quy tắc đặt tên biến JavaScript (không chứa khoảng trắng, ký tự đặc biệt...).