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

Hiển thị trường cụ thể trong mảng dùng $project, bỏ qua các trường khác trong MongoDB

Kết hợp $unwind và $project

$unwind bẻ mảng thành các bản ghi riêng, $project chọn trường cần giữ (1) hoặc loại bỏ (0).

Dữ liệu mẫu

> db.demo731.insertOne({
  ProductInformation: [
    { ProductId: "Product-1", ProductPrice: 80 },
    { ProductId: "Product-2", ProductPrice: 45 },
    { ProductId: "Product-3", ProductPrice: 50 }
  ]
});

Truy vấn: lấy ProductId nơi ProductPrice = 80, ẩn ProductPrice

db.demo731.aggregate([
  { $unwind: "$ProductInformation" },
  { $match: { "ProductInformation.ProductPrice": 80 } },
  { $project: { _id: 0, "ProductInformation.ProductPrice": 0 } }
]);

Kết quả

{ "ProductInformation": { "ProductId": "Product-1" } }

Chỉ hiển thị ProductId của sản phẩm giá 80.