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

Truy vấn trường mảng (list field) trong MongoDB: AND / OR logic

MongoDB cho phép truy vấn trực tiếp trên mảng. Khi truy vấn một giá trị đơn lẻ trên mảng, nó tương đương logic **OR** (khớp nếu bất kỳ phần tử nào bằng giá trị). Để kết hợp nhiều điều kiện, dùng $and, $or.

Ví dụ minh họa

Tạo collection andOrDemo với mảng StudentScore:

> db.andOrDemo.insertOne({ "StudentName": "Larry", "StudentScore": [33, 40, 50, 60, 70] });
> db.andOrDemo.insertOne({ "StudentName": "Larry", "StudentScore": [87, 67, 79, 98, 90] });

Hiển thị tất cả:

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

Kết quả:

{ "_id" : ..., "StudentName" : "Larry", "StudentScore" : [ 33, 40, 50, 60, 70 ] }
{ "_id" : ..., "StudentName" : "Larry", "StudentScore" : [ 87, 67, 79, 98, 90 ] }

Case 1: Tìm document mảng chứa giá trị 70 (Implicit OR)

> db.andOrDemo.find({ "StudentScore": 70 }).pretty();

Kết quả: Document 1 (vì mảng có 70).

{ "_id" : ..., "StudentName" : "Larry", "StudentScore" : [ 33, 40, 50, 60, 70 ] }

Case 2: Tìm document mảng chứa 60 HOẶC 90 ($or explicit)

> db.andOrDemo.find({ $or: [ { "StudentScore": 60 }, { "StudentScore": 90 } ] }).pretty();

Kết quả: Cả 2 document (doc1 có 60, doc2 có 90).

{ "_id" : ..., "StudentName" : "Larry", "StudentScore" : [ 33, 40, 50, 60, 70 ] }
{ "_id" : ..., "StudentName" : "Larry", "StudentScore" : [ 87, 67, 79, 98, 90 ] }

Case 3: Tìm document mảng chứa CẢ 60 VÀ 70 ($all - AND logic trên mảng)

> db.andOrDemo.find({ "StudentScore": { $all: [60, 70] } }).pretty();

Kết quả: Chỉ document 1 (có cả 60 và 70).

Tóm tắt logic trên mảng

Yêu cầuToán tử / Cú phápVí dụ
Chứa giá trị X{ arr: X }{ tags: "mongodb" }
Chứa ÍT NHẤT 1 trong [X, Y]{ $or: [ {arr:X}, {arr:Y} ] } hoặc { arr: { $in: [X,Y] } }{ tags: { $in: ["java", "go"] } }
Chứa TẤT CẢ [X, Y]{ arr: { $all: [X, Y] } }{ tags: { $all: ["java", "mongodb"] } }
KHÔNG chứa X{ arr: { $ne: X } } hoặc { arr: { $nin: [X] } }{ tags: { $nin: ["deprecated"] } }
Độ dài mảng = N{ arr: { $size: N } }{ tags: { $size: 3 } }

Lưu ý

  • $in hiệu quả hơn $or cho cùng field.
  • $all dùng index (multikey) nhưng quét nhiều hơn so với single value.
  • Tạo index: db.coll.createIndex({ "StudentScore": 1 }) tự động thành multikey index.