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

Lọc document MongoDB theo trường và trường con (subfield) với dot notation

Để lọc document theo trường con (subfield) của object lồng nhau, sử dụng dot notation (ký hiệu dấu chấm).

Tạo collection với dữ liệu không đồng nhất

> db.demo638.insert({Name:"Chris"});
> db.demo638.insert({Name:"David", details:{Subject:"MongoDB"}});

Hiển thị dữ liệu

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

Kết quả (2 document cấu trúc khác nhau):

{
  "_id" : ObjectId("5e9c28666c954c74be91e6de"), "Name" : "Chris"
}
{
  "_id" : ObjectId("5e9c28866c954c74be91e6df"),
  "Name" : "David", "details" : { "Subject" : "MongoDB" }
}

Lọc document KHÔNG CÓ details.Subject (hoặc null)

> db.demo638.find({"details.Subject": null});

Kết quả (chỉ document Chris - không có trường details):

{
  "_id" : ObjectId("5e9c28666c954c74be91e6de"), "Name" : "Chris"
}

Giải thích:

  • "details.Subject": Dot notation truy cập trường Subject bên trong object details
  • Trong MongoDB, truy vấn {field: null} khớp cả: (1) trường tồn tại và giá trị null, (2) **trường không tồn tại**
  • Document Chris không có trường details → details.Subject coi như null → khớp
  • Document David có details.Subject = "MongoDB" → không khớp

Để phân biệt null và missing field: Dùng $exists:

// Chỉ document có details.Subject = null (trường tồn tại)
db.demo638.find({ "details.Subject": null, "details.Subject": { $exists: true } })

// Document không có trường details.Subject (missing)
db.demo638.find({ "details.Subject": { $exists: false } })