Sử dụng $and để yêu cầu mảng chứa cả hai ID.
Tạo collection
> db.twoSpecificIdsDemo.insertOne({
PlayerId: 1,
"PlayerDetails": [
{ id: 100, "PlayerName": "Chris" },
{ id: 101, "PlayerName": "Sam" },
{ id: 102, "PlayerName": "Robert" },
{ id: 103, "PlayerName": "Carol" }
]
});
{ "acknowledged": true, "insertedId": ObjectId("5cd3e130edc6604c74817ce4") }
> db.twoSpecificIdsDemo.insertOne({
PlayerId: 1,
"PlayerDetails": [
{ id: 104, "PlayerName": "Mike" },
{ id: 105, "PlayerName": "Bob" },
{ id: 102, "PlayerName": "Ramit" },
{ id: 106, "PlayerName": "David" }
]
});
{ "acknowledged": true, "insertedId": ObjectId("5cd3e167edc6604c74817ce5") }
Hiển thị tất cả
> db.twoSpecificIdsDemo.find().pretty();
Tìm tài liệu có cả id=102 VÀ id=103 trong PlayerDetails
> db.twoSpecificIdsDemo.find({
$and: [
{ "PlayerDetails.id": 102 },
{ "PlayerDetails.id": 103 }
]
}).pretty();
Kết quả (chỉ tài liệu đầu tiên có cả 102 và 103):
{
"_id": ObjectId("5cd3e130edc6604c74817ce4"),
"PlayerId": 1,
"PlayerDetails": [
{ "id": 100, "PlayerName": "Chris" },
{ "id": 101, "PlayerName": "Sam" },
{ "id": 102, "PlayerName": "Robert" },
{ "id": 103, "PlayerName": "Carol" }
]
}
Giải thích: Mỗi điều kiện trong $and kiểm tra sự tồn tại của giá trị trong mảng. Tài liệu phải có cả hai giá trị (có thể ở phần tử khác nhau) mới khớp.