如何使用 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" } }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP