Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I return a document with filtered sub-documents using Mongo?
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 } ] }Advertisements