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
Query an array in MongoDB to fetch a specific value
To fetch a specific value from an array, use aggregate() along with $project. Let us create a collection with documents −
> db.demo761.insertOne(
... {
... "details": [
... {
... "student": {
... "FullName": "Chris Brown"
... }
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eb034d15637cd592b2a4af1")
}
> db.demo761.insertOne(
... {
... "details": [
... {
... "student": {
... "FullName": "Chris Taylor"
... }
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eb034d25637cd592b2a4af2")
}
Display all documents from a collection with the help of find() method −
> db.demo761.find();
This will produce the following output −
{ "_id" : ObjectId("5eb034d15637cd592b2a4af1"), "details" : [ { "student" : { "FullName" : "Chris Brown" } } ] }
{ "_id" : ObjectId("5eb034d25637cd592b2a4af2"), "details" : [ { "student" : { "FullName" : "Chris Taylor" } } ] }
Following is how to query an array in MongoDB −
> db.demo761.aggregate([
... {'$unwind':'$details'},
... {'$match': {
... 'details.student.FullName':'Chris Taylor',
... }},
... {'$project': {
... 'details.student.FullName': 1, '_id': 0
... }},
... ])
This will produce the following output −
{ "details" : { "student" : { "FullName" : "Chris Taylor" } } }Advertisements