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