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

Tương đương của WHERE IN(1,2,...) trong MongoDB?

Trong MongoDB, tương đương của mệnh đề WHERE IN(1,2,...) của SQL là toán tử $in. Cú pháp cơ bản như sau:

db.tênCollection.find({tênTrường: {$in: [giáTrị1, giáTrị2, ... N]}}).pretty();

Ví dụ minh họa

Trước tiên, tạo một collection với các document mẫu:

> db.whereInDemo.insertOne({"StudentName":"John","StudentMathScore":57});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca281ec6304881c5ce84ba5") }
> db.whereInDemo.insertOne({"StudentName":"Larry","StudentMathScore":89});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca281f56304881c5ce84ba6") }
> db.whereInDemo.insertOne({"StudentName":"Chris","StudentMathScore":98});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca281fd6304881c5ce84ba7") }
> db.whereInDemo.insertOne({"StudentName":"Robert","StudentMathScore":99});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca2820a6304881c5ce84ba8") }
> db.whereInDemo.insertOne({"StudentName":"Bob","StudentMathScore":97});
{ "acknowledged" : true, "insertedId" : ObjectId("5ca282206304881c5ce84ba9") }

Hiển thị tất cả document trong collection:

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

Kết quả:

{ "_id" : ObjectId("5ca281ec6304881c5ce84ba5"), "StudentName" : "John", "StudentMathScore" : 57 }
{ "_id" : ObjectId("5ca281f56304881c5ce84ba6"), "StudentName" : "Larry", "StudentMathScore" : 89 }
{ "_id" : ObjectId("5ca281fd6304881c5ce84ba7"), "StudentName" : "Chris", "StudentMathScore" : 98 }
{ "_id" : ObjectId("5ca2820a6304881c5ce84ba8"), "StudentName" : "Robert", "StudentMathScore" : 99 }
{ "_id" : ObjectId("5ca282206304881c5ce84ba9"), "StudentName" : "Bob", "StudentMathScore" : 97 }

Truy vấn với toán tử $in

Truy vấn tìm các sinh viên có điểm Toán là 97, 98 hoặc 99:

> db.whereInDemo.find({StudentMathScore:{$in:[97,98,99]}}).pretty();

Kết quả trả về:

{ "_id" : ObjectId("5ca281fd6304881c5ce84ba7"), "StudentName" : "Chris", "StudentMathScore" : 98 }
{ "_id" : ObjectId("5ca2820a6304881c5ce84ba8"), "StudentName" : "Robert", "StudentMathScore" : 99 }
{ "_id" : ObjectId("5ca282206304881c5ce84ba9"), "StudentName" : "Bob", "StudentMathScore" : 97 }

Toán tử $in cho phép so khớp một trường với nhiều giá trị trong một mảng, rất hữu ích khi cần lọc dữ liệu theo nhiều điều kiện giá trị rời rạc.