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
Perform nested document value search in MongoDB?
For searching value, use $match in MongoDB. Let us create a collection with documents −
> db.demo648.insertOne(
... {
... StudentInformation:
... [
... {
... Name:"John",
... CountryName:"US"
... },
... {
... Name:"David",
... CountryName:"AUS"
... },
... {
... Name:"Chris",
... CountryName:"US"
... },
... {
... Name:"Robert",
... CountryName:"UK"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c8b286c954c74be91e6f5")
}
Display all documents from a collection with the help of find() method −
> db.demo648.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c8b286c954c74be91e6f5"), "StudentInformation" : [
{ "Name" : "John", "CountryName" : "US" },
{ "Name" : "David", "CountryName" : "AUS" },
{ "Name" : "Chris", "CountryName" : "US" },
{ "Name" : "Robert", "CountryName" : "UK" }
] }
Following is the query to search for value in MongoDB −
> db.demo648.aggregate([
... { $unwind: "$StudentInformation" },
... { $match: { "StudentInformation.CountryName": "US" } },
... { $project: {_id: 0}}
... ])
This will produce the following output −
{ "StudentInformation" : { "Name" : "John", "CountryName" : "US" } }
{ "StudentInformation" : { "Name" : "Chris", "CountryName" : "US" } }Advertisements