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

Cách truy vấn theo danh sách _id trong MongoDB

Để tìm document theo danh sách các _id trong MongoDB, bạn sử dụng toán tử $in kết hợp với mảng ObjectId.

Ví dụ minh họa

Tạo collection và dữ liệu

> db.findListOfIdsDemo.insertOne({"StudentName":"Carol","StudentAge":21});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ecadd2f684a30fbdfd575") }
> db.findListOfIdsDemo.insertOne({"StudentName":"Bob","StudentAge":25});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ecae42f684a30fbdfd576") }
> db.findListOfIdsDemo.insertOne({"StudentName":"David","StudentAge":22});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ecaed2f684a30fbdfd577") }
> db.findListOfIdsDemo.insertOne({"StudentName":"John","StudentAge":20});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ecaf82f684a30fbdfd578") }
> db.findListOfIdsDemo.insertOne({"StudentName":"Mike","StudentAge":23});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8ecb092f684a30fbdfd579") }

Xem tất cả documents

> db.findListOfIdsDemo.find().pretty();
{
    "_id" : ObjectId("5c8ecadd2f684a30fbdfd575"),
    "StudentName" : "Carol",
    "StudentAge" : 21
}
{
    "_id" : ObjectId("5c8ecae42f684a30fbdfd576"),
    "StudentName" : "Bob",
    "StudentAge" : 25
}
{
    "_id" : ObjectId("5c8ecaed2f684a30fbdfd577"),
    "StudentName" : "David",
    "StudentAge" : 22
}
{
    "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"),
    "StudentName" : "John",
    "StudentAge" : 20
}
{
    "_id" : ObjectId("5c8ecb092f684a30fbdfd579"),
    "StudentName" : "Mike",
    "StudentAge" : 23
}

Truy vấn theo danh sách _id

> var listOfIds = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578'];
> var documentIds = listOfIds.map(function(myId) { return ObjectId(myId); });
> db.findListOfIdsDemo.find({_id: {$in: documentIds }}).pretty();
{
    "_id" : ObjectId("5c8ecae42f684a30fbdfd576"),
    "StudentName" : "Bob",
    "StudentAge" : 25
}
{
    "_id" : ObjectId("5c8ecaf82f684a30fbdfd578"),
    "StudentName" : "John",
    "StudentAge" : 20
}

Giải thích các bước

  1. Khai báo mảng string ID: listOfIds
  2. Chuyển string thành ObjectId: .map(function(id) { return ObjectId(id); })
  3. Query với $in: {_id: {$in: documentIds}}

Cách viết gọn hơn (MongoDB shell)

var ids = ['5c8ecae42f684a30fbdfd576', '5c8ecaf82f684a30fbdfd578'].map(ObjectId);
db.findListOfIdsDemo.find({_id: {$in: ids}}).pretty();

Ứng dụng thực tế

// Lấy danh sách ID từ query khác
var topStudentIds = db.grades.find({score: {$gte: 90}}).map(function(doc) { return doc.studentId; });

// Query chi tiết student
db.students.find({_id: {$in: topStudentIds}}).pretty();

Lưu ý

  • $in hoạt động hiệu quả với index trên _id (mặc định đã có)
  • Giới hạn: $in array không nên quá lớn (>1000 elements) → chia batch
  • Nếu ID là string (không phải ObjectId), không cần chuyển đổi
  • Thứ tự kết quả không đảm bảo theo thứ tự mảng $in → cần sort thêm nếu cần

Sắp xếp theo thứ tự mảng ID

var ids = [...].map(ObjectId);
var docs = db.coll.find({_id: {$in: ids}}).toArray();
// Sắp xếp lại theo thứ tự ids
docs.sort(function(a, b) {
    return ids.indexOf(a._id) - ids.indexOf(b._id);
});