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

Hiển thị bản ghi MongoDB theo ObjectId

Để truy xuất tài liệu cụ thể bằng ObjectId trong MongoDB, có thể sử dụng trực tiếp trong điều kiện find() hoặc findOne(). ObjectId là khóa chính mặc định (_id) của mọi tài liệu.

Tạo dữ liệu mẫu

> db.findByObjectIdDemo.insertOne({"ClientName":"Larry","ClientAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd68cd657806ebf1256f11a") }
> db.findByObjectIdDemo.insertOne({"ClientName":"Chris","ClientAge":26});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd68cdc57806ebf1256f11b") }
> db.findByObjectIdDemo.insertOne({"ClientName":"David","ClientAge":38,"isMarried":true});
{ "acknowledged" : true, "insertedId" : ObjectId("5cd68cf657806ebf1256f11c") }

Xem tất cả tài liệu

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

Tìm theo ObjectId với find()

> db.findByObjectIdDemo.find({_id: new ObjectId("5cd68cf657806ebf1256f11c")}).toArray(function(err, myDocument) { 
  console.log(myDocument); 
});

Kết quả


Các cách truy vấn theo ObjectId

1. findOne() - Trả về tài liệu đơn (khuyên dùng)

db.findByObjectIdDemo.findOne({_id: ObjectId("5cd68cf657806ebf1256f11c")});

2. find() - Trả về cursor (cần toArray() hoặc forEach)

db.findByObjectIdDemo.find({_id: ObjectId("5cd68cf657806ebf1256f11c")});

3. Trong ứng dụng (Node.js driver)

const { ObjectId } = require('mongodb');
const doc = await collection.findOne({_id: new ObjectId("5cd68cf657806ebf1256f11c")});

4. Chuyển đổi từ String sang ObjectId

// Trong shell
var idStr = "5cd68cf657806ebf1256f11c";
db.findByObjectIdDemo.findOne({_id: ObjectId(idStr)});

// Trong ứng dụng
const doc = await collection.findOne({_id: new ObjectId(idString)});

Cấu trúc ObjectId

ObjectId 12 bytes bao gồm:

  • 4 bytes: Timestamp (giây từ epoch)
  • 5 bytes: Giá trị ngẫu nhiên (machine + process)
  • 3 bytes: Counter (tăng dần)

Do đó ObjectId tăng dần theo thời gian, có thể dùng để sắp xếp theo thời gian tạo.

Lấy timestamp từ ObjectId

ObjectId("5cd68cf657806ebf1256f11c").getTimestamp();
// ISODate("2019-05-11T08:53:01Z")

Lưu ý

  • Luôn dùng ObjectId() constructor, không so sánh chuỗi trực tiếp
  • findOne() hiệu quả hơn find().limit(1) cho truy vấn khóa chính
  • ObjectId tự động tạo khi insert nếu không cung cấp _id