
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
MongoDB query to find and return subdocument with criteria?
Let us create a collection with documents −
> db.demo345.insertOne({ ... "UserName" : "Robert", ... "UserDetails" : [ ... { ... "isMarried" : false, ... "CountryName":"US" ... ... }, ... { ... "isMarried" : true, ... "CountryName":"UK" ... ... }, ... { ... "isMarried" : false, ... "CountryName":"AUS" ... ... } ... ] ... } ... ) { "acknowledged" : true, "insertedId" : ObjectId("5e5404fdf8647eb59e5620ac") }
Display all documents from a collection with the help of find() method −
> db.demo345.find();
This will produce the following output −
{ "_id" : ObjectId("5e5404fdf8647eb59e5620ac"), "UserName" : "Robert", "UserDetails" : [ { "isMarried" : false, "CountryName" : "US" }, { "isMarried" : true, "CountryName" : "UK" }, { "isMarried" : false, "CountryName" : "AUS" } ] }
Following is the query to find and then return subdocument with criteria −
> db.demo345.aggregate([ ... { ... $match: { UserName: "Robert" } ... }, ... { ... $addFields: { ... UserDetails: { ... $filter: { ... input: "$UserDetails", ... cond: { ... $eq: [ "$$this.isMarried", true ] ... } ... } ... } ... } ... } ... ])
This will produce the following output −
{ "_id" : ObjectId("5e5404fdf8647eb59e5620ac"), "UserName" : "Robert", "UserDetails" : [ { "isMarried" : true, "CountryName" : "UK" } ] }
- Related Questions & Answers
- Query MongoDB with length criteria?
- MongoDB query to find value in array with multiple criteria (range)
- How to sort, select and query subdocument in MongoDB?
- MongoDB query to remove subdocument from document?
- Query MongoDB subdocument to print on one line?
- Display MongoDB with document and subdocument example and update
- Find value in a MongoDB Array with multiple criteria?
- How to filter array in subdocument with MongoDB?
- MongoDB query to find documents having two values in an array conforming to multiple criteria?
- MongoDB query on nth element (variable index) of subdocument array
- MongoDB query to find documents with specific FirstName and LastName
- MongoDB query to count records on the basis of matching criteria
- How to query documents by a condition on the subdocument in MongoDB?
- MongoDB to sort by subdocument match?
- Finding a specific item in subdocument with MongoDB?
Advertisements