Có, sử dụng $in nhanh hơn đáng kể so với thực hiện nhiều truy vấn find() đơn lẻ. Tạo collection:
> db.demo653.insertOne({subject:"MySQL"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04b274deddd72997713c0") }
> db.demo653.insertOne({subject:"MongoDB"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04b304deddd72997713c1") }
> db.demo653.insertOne({subject:"Java"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04b354deddd72997713c2") }
> db.demo653.insertOne({subject:"C"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04b384deddd72997713c3") }
> db.demo653.insertOne({subject:"C++"});
{ "acknowledged" : true, "insertedId" : ObjectId("5ea04b3b4deddd72997713c4") }
Hiển thị dữ liệu:
> db.demo653.find();
Kết quả:
Một truy vấn
$intìm 3 môn học (MySQL, C++, C):> db.demo653.find({subject:{$in:["MySQL","C++","C"]}});Kết quả 3 tài liệu khớp:
Tại sao $in nhanh hơn?
- 1 round-trip network thay vì N round-trips
- 1 lần parse/plan/execute query plan thay vì N lần
- Index scan duy nhất - MongoDB dùng index intersection hoặc scan index một lần
- Giảm overhead driver, connection pooling, network latency
Lưu ý: Với mảng $in quá lớn (>1000 phần tử), hiệu suất có thể giảm. Cân nhắc split thành nhiều batch hoặc dùng $or với hint index. Tránh dùng $in với regex (không dùng index hiệu quả).