How do I return a document with filtered sub-documents using Mongo?

MongoDBDatabaseBig Data Analytics

For this, use $project in MongoDB. Within that, use $filter. Let us create a collection with documents −

> db.demo457.insertOne(
... {
...    _id: 101,
...    details: [
...       { ProductName:"Product-1" , ProductPrice:90 },
...       { ProductName:"Product-2" , ProductPrice:190 }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }
>
> db.demo457.insertOne(
... {
...    _id: 102,
...    details: [
...       { ProductName:"Product-3" , ProductPrice:150},
...       { ProductName:"Product-4" , ProductPrice:360 }
...    ]
... }
... );
{ "acknowledged" : true, "insertedId" : 102 }

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

> db.demo457.find();

This will produce the following output −

{ "_id" : 101, "details" : [ { "ProductName" : "Product-1", "ProductPrice" : 90 }, { "ProductName"
: "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-3", "ProductPrice" : 150 }, {
"ProductName" : "Product-4", "ProductPrice" : 360 } ] }

Following is the query to return a document with filtered sub-documents using MongoDB −

> db.demo457.aggregate([
... {
...    $project: {
...       details: {
...          $filter: {
...             input: "$details",
...             as: "output",
...             cond: { $gte: [ "$$output.ProductPrice", 170 ] }
...          }
...       }
...    }
... }
... ])

This will produce the following output −

{ "_id" : 101, "details" : [ { "ProductName" : "Product-2", "ProductPrice" : 190 } ] }
{ "_id" : 102, "details" : [ { "ProductName" : "Product-4", "ProductPrice" : 360 } ] }
raja
Published on 11-May-2020 09:18:38
Advertisements