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

Lấy tất cả embedded document có trạng thái isMarried trong MongoDB

Dùng $project trong aggregate để trích xuất (project) chỉ các trường lồng nhau (embedded document) cần thiết.

Dữ liệu mẫu

> db.demo220.insertOne({ "id":101, "FullName": "John Doe", "EmailId": "john12@gmail.com", "ShippingDate": new ISODate(), "details": { "_id": 1001, "isMarried": true } });
> db.demo220.insertOne({ "id":102, "FullName": "John Smith", "EmailId": "johnsmith@gmail.com", "ShippingDate": new ISODate(), "details": { "_id": 1002, "isMarried": false } });

Pipeline aggregate $project

> db.demo220.aggregate({ $project: { "isMarried": "$details.isMarried", "detailsId": "$details._id" } });

Kết quả

{ "_id" : ObjectId("5e3eaf5b03d395bdc213471d"), "isMarried" : true }
{ "_id" : ObjectId("5e3eaf5c03d395bdc213471e"), "isMarried" : false }

Giải thích:

  • $project: Chỉ định trường output. 1 = include, 0 = exclude
  • "isMarried": "$details.isMarried": Tạo trường mới isMarried từ đường dẫn lồng nhau
  • "detailsId": "$details._id": Trích xuất _id của embedded document
  • _id của document gốc tự động giữ lại (trừ khi "_id": 0)

Mở rộng: Nếu details là mảng, dùng $map hoặc $unwind + $project. Nếu cần lọc, thêm $match trước $project.