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

Cách tìm document bằng ObjectId trong MongoDB

Để truy xuất một document cụ thể bằng _id (kiểu ObjectId), bạn cần dùng hàm ObjectId() bao quanh chuỗi ID.

Cú pháp

db.collection.find({ "_id": ObjectId("chuỗi_id_24_ký_tự") }).pretty();

Ví dụ minh họa

Tạo collection findDocumentWithObjectIdDemo:

> db.findDocumentWithObjectIdDemo.insertOne({"UserName": "Larry"});
> db.findDocumentWithObjectIdDemo.insertOne({"UserName": "Mike", "UserAge": 23});
> db.findDocumentWithObjectIdDemo.insertOne({"UserName": "Carol", "UserAge": 26, "UserHobby": ["Learning", "Photography"]});

Hiển thị tất cả:

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

Kết quả:

{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" }
{ "_id" : ObjectId("5c90e4444afe5c1d2279d69c"), "UserName" : "Mike", "UserAge" : 23 }
{ "_id" : ObjectId("5c90e4704afe5c1d2279d69d"), "UserName" : "Carol", "UserAge" : 26, "UserHobby" : [ "Learning", "Photography" ] }

Truy vấn theo ObjectId

Trường hợp 1: Tìm document của Carol

> db.findDocumentWithObjectIdDemo.find({ "_id": ObjectId("5c90e4704afe5c1d2279d69d") }).pretty();

Kết quả:

{ "_id" : ObjectId("5c90e4704afe5c1d2279d69d"), "UserName" : "Carol", "UserAge" : 26, "UserHobby" : [ "Learning", "Photography" ] }

Trường hợp 2: Tìm document của Mike

> db.findDocumentWithObjectIdDemo.find({ "_id": ObjectId("5c90e4444afe5c1d2279d69c") }).pretty();

Kết quả:

{ "_id" : ObjectId("5c90e4444afe5c1d2279d69c"), "UserName" : "Mike", "UserAge" : 23 }

Lưu ý khi dùng driver (Node.js, Python, Java...)

  • Node.js (Native driver): const { ObjectId } = require('mongodb'); db.collection.findOne({ _id: new ObjectId("id_string") })
  • Python (PyMongo): from bson.objectid import ObjectId; db.collection.find_one({"_id": ObjectId("id_string")})
  • Mongoose (ODM): Tự động cast string thành ObjectId khi dùng findById("id_string").

Cảnh báo: Không tìm kiếm bằng chuỗi thô { "_id": "5c90e470..." } vì nó sẽ không khớp (kiểu dữ liệu khác nhau).