如何使用 MongoDB 中的 $project 在陣列中顯示特定欄位並忽略其他欄位?


要顯示特定欄位,請使用 $project 以及 $unwind。要忽略欄位,請將值設定為 0。讓我們用文件建立一個集合 -

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

使用 find() 方法顯示來自集合的所有文件 -

> db.demo731.find();

這將生成以下輸出 -

{ "_id" : ObjectId("5eac5efd56e85a39df5f6341"), "ProductInformation" : [ { "ProductId" : "Product-1", "ProductPrice" : 80 }, { "ProductId" : "Product-2", "ProductPrice" : 45 }, { "ProductId" : "Product-3", "ProductPrice" : 50 } ] }

以下是使用 MongoDB 中的 $project 在陣列中顯示特定欄位的查詢 -

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

這將生成以下輸出 -

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

更新於:2020年5月15日

780 人瀏覽

開啟您的 職業生涯

完成課程進行認證

立即開始
廣告
© . All rights reserved.