如何在 MongoDB 中使用 $project 显示数组中的特定字段并忽略其他字段?
mongodbdatabasebig data analytics更新于 2026/2/11 4:37:17
要显示特定字段,请使用 $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" } }

