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
How to project specific fields from a document inside an array in Mongodb?
To project specific fields from a document inside an array, you can use positional ($) operator.
Let us first create a collection with documents
> db.projectSpecificFieldDemo.insertOne(
... {
... "UniqueId": 101,
... "StudentDetails" : [{"StudentName" : "Chris", "StudentCountryName ": "US"},
... {"StudentName" : "Robert", "StudentCountryName" : "UK"},
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca27aeb6304881c5ce84ba2")
}
> db.projectSpecificFieldDemo.insertOne( { "UniqueId": 102, "StudentDetails" :
[{"StudentName" : "Robert", "StudentCountryName ": "UK"}, {"StudentName" : "David",
"StudentCountryName" : "AUS"}, ] } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ca27b106304881c5ce84ba3")
}
Following is the query to display all documents from a collection with the help of find() method
> db.projectSpecificFieldDemo.find().pretty();
This will produce the following output
{
"_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
"UniqueId" : 101,
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentCountryName " : "US"
},
{
"StudentName" : "Robert",
"StudentCountryName" : "UK"
}
]
}
{
"_id" : ObjectId("5ca27b106304881c5ce84ba3"),
"UniqueId" : 102,
"StudentDetails" : [
{
"StudentName" : "Robert",
"StudentCountryName " : "UK"
},
{
"StudentName" : "David",
"StudentCountryName" : "AUS"
}
]
}
Following is the query to project specific fields from a document inside an array
> var myDocument = { UniqueId : 101, 'StudentDetails.StudentName' : 'Chris' };
> var myProjection= {'StudentDetails.$': 1 };
> db.projectSpecificFieldDemo.find(myDocument , myProjection).pretty();
This will produce the following output
{
"_id" : ObjectId("5ca27aeb6304881c5ce84ba2"),
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentCountryName " : "US"
}
]
}Advertisements