
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
Filter Specific Values from a MongoDB Document
To filter specific values, use $filter in MongoDB. Let us create a collection with documents −
> db.demo751.insertOne( ... { ... _id: 101, ... details: [ ... { Name: "Robert", id:110,Age:21}, ... { Name: "Rae", id:110,Age:22}, ... {Name: "Ralph", id:116,Age:23} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo751.find().pretty();
This will produce the following output −
{ "_id" : 101, "details" : [ { "Name" : "Robert", "id" : 110, "Age" : 21 }, { "Name" : "Rae", "id" : 110, "Age" : 22 }, { "Name" : "Ralph", "id" : 116, "Age" : 23 } ] }
Following is the query to filter −
> db.demo751.aggregate([ ... { ... $addFields: { ... details: { ... $let: { ... vars: { ... filtered: { $filter: { input: "$details", as: "out", cond: { $eq: [ "$$out.id", 110 ] } } } ... }, ... in: { $slice: [ "$$filtered", -1 ] } ... } ... } ... } ... } ... ])
This will produce the following output −
{ "_id" : 101, "details" : [ { "Name" : "Rae", "id" : 110, "Age" : 22 } ] }
Advertisements