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
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" }
]
}Advertisements