Toán tử $in chọn tài liệu mà giá trị trường khớp với bất kỳ giá trị nào trong mảng cho trước. Rất hiệu quả cho truy vấn "IN" kiểu SQL, thay thế nhiều điều kiện $or.
Dữ liệu mẫu
> db.demo161.insertOne({"ClientId":101,"ClientName":"Chris"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577cafdf09dd6d0853a09") }
> db.demo161.insertOne({"ClientId":102,"ClientName":"David"});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577d0fdf09dd6d0853a0a") }
> db.demo161.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577dffdf09dd6d0853a0b") }
> db.demo161.insertOne({"ClientId":104,"ClientName":"Carol","ClientAge":31});
{ "acknowledged" : true, "insertedId" : ObjectId("5e3577eefdf09dd6d0853a0c") }
Xem dữ liệu
> db.demo161.find();
{ "_id" : ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId" : 101, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e3577d0fdf09dd6d0853a0a"), "ClientId" : 102, "ClientName" : "David" }
{ "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31 }
Truy vấn: ClientId IN (101, 103, 104)
> db.demo161.find({ClientId:{$in:[101,103,104]}});
Kết quả
{ "_id" : ObjectId("5e3577cafdf09dd6d0853a09"), "ClientId" : 101, "ClientName" : "Chris" }
{ "_id" : ObjectId("5e3577dffdf09dd6d0853a0b"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }
{ "_id" : ObjectId("5e3577eefdf09dd6d0853a0c"), "ClientId" : 104, "ClientName" : "Carol", "ClientAge" : 31 }
Mẹo: $in có thể dùng với mảng giá trị bất kỳ kiểu (string, number, ObjectId). Có index trên ClientId sẽ làm truy vấn rất nhanh. Ngược lại, $nin (not in) loại trừ các giá trị trong mảng.