Để tìm document bằng _id (kiểu ObjectId), bắt buộc dùng hàm ObjectId() bao quanh chuỗi 24 ký tự hex. Truyền chuỗi thô sẽ không khớp.
Cú pháp
db.collection.find({ "_id": ObjectId("chuỗi_id_24_ký_tự") }).pretty();
Ví dụ minh họa
Tạo collection searchDocumentDemo 6 document:
> db.searchDocumentDemo.insertOne({ "UserId": 1, "UserName": "Larry" });
> db.searchDocumentDemo.insertOne({ "UserId": 2, "UserName": "Mike" });
> db.searchDocumentDemo.insertOne({ "UserId": 3, "UserName": "David" });
> db.searchDocumentDemo.insertOne({ "UserId": 4, "UserName": "Chris" });
> db.searchDocumentDemo.insertOne({ "UserId": 5, "UserName": "Robert" });
> db.searchDocumentDemo.insertOne({ "UserId": 6, "UserName": "Sam" });
Hiển thị tất cả:
> db.searchDocumentDemo.find().pretty();
Kết quả:
{ "_id" : ObjectId("5c97a8e4330fd0aa0d2fe487"), "UserId" : 1, "UserName" : "Larry" }
{ "_id" : ObjectId("5c97a8ea330fd0aa0d2fe488"), "UserId" : 2, "UserName" : "Mike" }
{ "_id" : ObjectId("5c97a8f1330fd0aa0d2fe489"), "UserId" : 3, "UserName" : "David" }
{ "_id" : ObjectId("5c97a8fa330fd0aa0d2fe48a"), "UserId" : 4, "UserName" : "Chris" }
{ "_id" : ObjectId("5c97a901330fd0aa0d2fe48b"), "UserId" : 5, "UserName" : "Robert" }
{ "_id" : ObjectId("5c97a911330fd0aa0d2fe48c"), "UserId" : 6, "UserName" : "Sam" }
Tìm document có _id = ObjectId("5c97a901330fd0aa0d2fe48b")
> db.searchDocumentDemo.find({ "_id": ObjectId("5c97a901330fd0aa0d2fe48b") }).pretty();
Kết quả:
{ "_id" : ObjectId("5c97a901330fd0aa0d2fe48b"), "UserId" : 5, "UserName" : "Robert" }
Trong các Driver phổ biến
| Driver | Cú pháp |
|---|---|
| Node.js (Native) | const { ObjectId } = require('mongodb'); coll.findOne({ _id: new ObjectId("5c97a901...") }) |
| Python (PyMongo) | from bson.objectid import ObjectId; coll.find_one({"_id": ObjectId("5c97a901...")}) |
| Mongoose (ODM) | Model.findById("5c97a901...") (tự cast string -> ObjectId) |
| C# (.NET) | ObjectId.Parse("5c97a901...") hoặc new ObjectId("5c97a901...") |
| Java (Sync) | new ObjectId("5c97a901...") |
| Go (mongo-driver) | primitive.ObjectIDFromHex("5c97a901...") |
Lỗi thường gặp
- Sai:
db.coll.find({ _id: "5c97a901..." })-> Không trả kết quả (string != ObjectId). - Sai:
db.coll.find({ _id: ObjectId("5c97a901") })-> Lỗi: "Invalid object id: length must be 24". - Đúng: Luôn dùng
ObjectId("chuỗi_24_ký_tự_hex").
Mẹo: Lấy ObjectId từ _id string trong shell
var id = ObjectId("5c97a901330fd0aa0d2fe48b");
db.searchDocumentDemo.find({ _id: id });