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
Find the document by field name with a specific value in MongoDB?
To find the document by field name with a specific value, you can use $exists operator. Let us create a collection with documents
> db.findByFieldName.insertOne( { "Client":{ "ClientDetails":{ "ClientName":"Larry", "ClientAge":29 }, "ClientProjectDetails":{ "ProjectName":"Online Book Store", "TeamSize":10, "TechnologyUsed":"Spring Boot" } } } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9e93b2d628fa4220163b64")
}
> db.findByFieldName.insertOne({
... " Client":{
... " ClientDetails":{
... " ClientName":"Chris",
... " ClientAge":27
... },
... "ClientEducationDetails":{
... " isEducated":true,
... "CollegeName":"M.I.T."
...
... }
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9e9421d628fa4220163b65")
}
Following is the query to display all documents from a collection with the help of find() method
> db.findByFieldName.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5c9e93b2d628fa4220163b64"),
"Client" : {
"ClientDetails" : {
"ClientName" : "Larry",
"ClientAge" : 29
},
"ClientProjectDetails" : {
"ProjectName" : "Online Book Store",
"TeamSize" : 10,
"TechnologyUsed" : "Spring Boot"
}
}
}
{
"_id" : ObjectId("5c9e9421d628fa4220163b65"),
"Client" : {
"ClientDetails" : {
"ClientName" : "Chris",
"ClientAge" : 27
},
"ClientEducationDetails" : {
"isEducated" : true,
"CollegeName" : "M.I.T."
}
}
}
Following is the query to find the document by field name
> db.findByFieldName.find({"Client.ClientProjectDetails":{$exists: true}}).pretty();
This will produce the following output
{
"_id" : ObjectId("5c9e93b2d628fa4220163b64"),
"Client" : {
"ClientDetails" : {
"ClientName" : "Larry",
"ClientAge" : 29
},
"ClientProjectDetails" : {
"ProjectName" : "Online Book Store",
"TeamSize" : 10,
"TechnologyUsed" : "Spring Boot"
}
}
}Advertisements