Để tìm tài liệu có mảng chứa **TẤT CẢ** các giá trị chỉ định, sử dụng toán tử $all. Tạo collection với index:
> db.demo668.createIndex({"ListOfSubject":1});
{ "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }
> db.demo668.insert({"ListOfSubject":["MySQL","Java","C"]});
WriteResult({ "nInserted" : 1 })
> db.demo668.insert({"ListOfSubject":["MongoDB","Python","C++"]});
WriteResult({ "nInserted" : 1 })
> db.demo668.insert({"ListOfSubject":["C#","Spring","Hibernate","MongoDB"]});
WriteResult({ "nInserted" : 1 })
Hiển thị dữ liệu:
> db.demo668.find();
Kết quả:
Tìm tài liệu có ListOfSubject chứa **CẢ** "MongoDB" VÀ "C++":
> db.demo668.find({"ListOfSubject":{ $all:["MongoDB","C++"]}});Kết quả chỉ khớp tài liệu thứ 2 (có cả MongoDB và C++):
So sánh $all vs $in:
| Toán tử | Ý nghĩa | Ví dụ khớp |
|---|---|---|
$in: ["A","B"] | Chứa A **HOẶC** B (hoặc cả hai) | ["A"], ["B"], ["A","B"], ["A","C"] |
$all: ["A","B"] | Chứa **CẢ** A **VÀ** B | ["A","B"], ["B","A","C"] |