Trường _id trong MongoDB là một trường bắt buộc. Mỗi tài liệu được lưu trữ trong một collection đều yêu cầu một trường _id duy nhất đóng vai trò là khóa chính. Dưới đây là cú pháp để lấy mảng tất cả các _id trong MongoDB:
db.yourCollectionName.find({ _id : { $in : [yourValue1, yourValue2, yourValue3, ... N] } });
Đầu tiên, hãy tạo một collection với các tài liệu mẫu:
> db.selectInWhereIdDemo.insertOne({"_id":23}); { "acknowledged" : true, "insertedId" : 23 }
> db.selectInWhereIdDemo.insertOne({"_id":28}); { "acknowledged" : true, "insertedId" : 28 }
> db.selectInWhereIdDemo.insertOne({"_id":45}); { "acknowledged" : true, "insertedId" : 45 }
> db.selectInWhereIdDemo.insertOne({"_id":75}); { "acknowledged" : true, "insertedId" : 75 }
> db.selectInWhereIdDemo.insertOne({"_id":85}); { "acknowledged" : true, "insertedId" : 85 }
>> db.selectInWhereIdDemo.insertOne({"_id":145}); { "acknowledged" : true, "insertedId" : 145 }
Truy vấn hiển thị tất cả tài liệu từ collection bằng phương thức find():
> db.selectInWhereIdDemo.find().pretty();
Kết quả trả về:
{ "_id" : 23 } { "_id" : 28 } { "_id" : 45 } { "_id" : 75 } { "_id" : 85 } { "_id" : 145 }
Truy vấn để lấy các _id cụ thể trong một mảng:
> db.selectInWhereIdDemo.find({ _id : { $in : [23, 45, 85, 145] } });
Kết quả:
{ "_id" : 23 } { "_id" : 45 } { "_id" : 85 } { "_id" : 145 }