如何使用 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.