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

Tìm document khi tất cả phần tử mảng có giá trị cụ thể trong MongoDB

Sử dụng $not kết hợp $elemMatch với $ne để tìm document mà TẤT CẢ phần tử mảng đều bằng giá trị cho trước.

Tạo collection với document:

> db.findDocumentsDemo.insertOne(
    { _id: 101, "ProductDetails": [ { "ProductValue": 100 }, { "ProductValue": 120 } ] }
); { "acknowledged" : true, "insertedId" : 101 }
> db.findDocumentsDemo.insertOne(
    { _id: 102, "ProductDetails": [ { "ProductValue": 120 }, { "ProductValue": 120 }, { "ProductValue": 120 } ] }
); { "acknowledged" : true, "insertedId" : 102 }

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

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

Kết quả:

{ "_id" : 101, "ProductDetails" : [ { "ProductValue" : 100 }, { "ProductValue" : 120 } ] }
{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }

Truy vấn tìm document mà TẤT CẢ ProductValue trong mảng ProductDetails đều = 120:

> db.findDocumentsDemo.find({
  "ProductDetails.ProductValue": { },
  "ProductDetails": {
    $not: {
      $elemMatch: {
        "ProductValue": { $ne: 120 }
      }
    }
  }
});

Kết quả (chỉ document _id: 102 thỏa mãn):

{ "_id" : 102, "ProductDetails" : [ { "ProductValue" : 120 }, { "ProductValue" : 120 }, { "ProductValue" : 120 } ] }

Giải thích: Logic là "KHÔNG TỒN TẠI phần tử nào có ProductValue != 120" → TẤT CẢ đều = 120.