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

Lọc theo nhiều phần tử mảng trong MongoDB

Sử dụng toán tử $elemMatch để khớp document chứa mảng có ít nhất một phần tử thỏa mãn tất cả tiêu chí. Tạo collection:

> db.filterBySeveralElementsDemo.insertOne(
  {
    "_id": 100,
    "StudentDetails": [
      { "StudentName": "John", "StudentCountryName": "US" },
      { "StudentName": "Carol", "StudentCountryName": "UK" }
    ]
  }
);
{ "acknowledged": true, "insertedId": 100 }
> db.filterBySeveralElementsDemo.insertOne(
  {
    "_id": 101,
    "StudentDetails": [
      { "StudentName": "Sam", "StudentCountryName": "AUS" },
      { "StudentName": "Chris", "StudentCountryName": "US" }
    ]
  }
);
{ "acknowledged": true, "insertedId": 101 }

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

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

Kết quả:

{
  "_id": 100,
  "StudentDetails": [
    { "StudentName": "John", "StudentCountryName": "US" },
    { "StudentName": "Carol", "StudentCountryName": "UK" }
  ]
}
{
  "_id": 101,
  "StudentDetails": [
    { "StudentName": "Sam", "StudentCountryName": "AUS" },
    { "StudentName": "Chris", "StudentCountryName": "US" }
  ]
}

Truy vấn lọc theo nhiều phần tử mảng (tìm StudentName="Sam" VÀ StudentCountryName="AUS"):

> db.filterBySeveralElementsDemo.find({
  StudentDetails: {
    $elemMatch: { StudentName: 'Sam', StudentCountryName: 'AUS' }
  }
}).pretty();

Kết quả:

{
  "_id": 101,
  "StudentDetails": [
    { "StudentName": "Sam", "StudentCountryName": "AUS" },
    { "StudentName": "Chris", "StudentCountryName": "US" }
  ]
}