- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Display only an element found in an array in MongoDB?
To display only an element found in an array, use aggregate(). Let us create a collection with documents −
> db.demo204.insertOne( ... { ... "_id" : 101, ... "Name" : "Chris", ... "Age" : 23, ... "details" : [ ... { ... "id" : "1001", ... "empId" : "John_1001", ... "salary" : "50000", ... "Technology" : "Java" ... }, ... { ... "id" : "1002", ... "empId" : "John_1002" ... }, ... { ... "id" : "1003", ... "empId" : "John_10003", ... "salary" : "60000", ... "Technology" : "MongoDB" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo204.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris", "Age" : 23, "details" : [ { "id" : "1001", "empId" : "John_1001", "salary" : "50000", "Technology" : "Java" }, { "id" : "1002", "empId" : "John_1002" }, { "id" : "1003", "empId" : "John_10003", "salary" : "60000", "Technology" : "MongoDB" } ] }
Following is the query to display only an element found in an array in MongoDB −
> db.demo204.aggregate( ... [ ... { "$match": { "details.id": "1001" }}, ... { "$unwind": "$details" }, ... { "$match": { "details.id":"1001" }}, ... { "$project": { "Technology": "$details.Technology", "_id":0 }} ... ] ...)
This will produce the following output −
{ "Technology" : "Java" }
- Related Articles
- Retrieve only the queried element in an object array in MongoDB collection?
- How to delete element from an array in MongoDB?
- How to push an element into array in MongoDB?
- Pull an element in sub of sub-array in MongoDB?
- Increment value of an array element with array object in MongoDB
- Find the only different element in an array using C++
- Getting only the first item for an array property in MongoDB?
- Unset an attribute from a single array element in MongoDB?
- How do you limit an array sub-element in MongoDB?
- Removing an array element from a MongoDB collection
- How to remove an array element by its index in MongoDB?
- Update an array element matching a condition using $push in MongoDB
- C# Program to display the first element from an array
- Get the first element in an array and return using MongoDB Aggregate?
- Increment a property value of an element in array object with MongoDB

Advertisements