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

Kiểm tra giá trị có trong mảng MongoDB với $in

Để kiểm tra giá trị có trong mảng, sử dụng toán tử $in. Tạo collection:

> db.testInArray.insertOne({"ListOfNumbers":[10,56,78,90,32]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04d42df5e889d7a519950d") }
> db.testInArray.insertOne({"ListOfNumbers":[56,78,91,100]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e04d588f5e889d7a519950e") }

Hiển thị tài liệu:

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

Tìm tài liệu có ListOfNumbers chứa giá trị 90:

> db.testInArray.find({ ListOfNumbers: { "$in" : [90] } });

Kết quả - chỉ tài liệu đầu tiên có 90:

Giải thích: {$in: [90]} tương đương với ListOfNumbers == 90 khi 90 là phần tử mảng. $in thường dùng với mảng nhiều giá trị: {$in: [90, 100, 200]} tìm tài liệu chứa BẤT KỲ giá trị nào trong mảng.