How to display a specific field in array using $project in MongoDB and ignore other fields?

MongoDBDatabaseBig Data Analytics

To display a specific field, use $project along with $unwind. To ignore a field, set to 0. Let us create a collection with documents −

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

Display all documents from a collection with the help of find() method −

> db.demo731.find();

This will produce the following output −

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

Following is the query to display a specific field in array using $project in MongoDB −

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

This will produce the following output −

{ "ProductInformation" : { "ProductId" : "Product-1" } }
raja
Published on 15-May-2020 12:51:26
Advertisements