
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
MongoDB Query to Find Property of First Element of Array
You can use $slice operator for this. Let us first create a collection with documents −
> db.firstElementOfArray.insertOne( ... { ... _id: 100, ... "Details": [ ... { ... "CustomerName": "John", ... "CustomerCountryName":"US" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 100 } > db.firstElementOfArray.insertOne( ... { ... _id: 101, ... "Details": [ ... { ... "CustomerName": "Carol", ... "CustomerCountryName":"UK" ... }, ... { ... "CustomerName": "David", ... "CustomerCountryName":"AUS" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from the collection with the help of find() method −
> db.firstElementOfArray.find().pretty();
This will produce the following output −
{ "_id" : 100, "Details" : [ { "CustomerName" : "John", "CustomerCountryName" : "US" } ] } { "_id" : 101, "Details" : [ { "CustomerName" : "Carol", "CustomerCountryName" : "UK" }, { "CustomerName" : "David", "CustomerCountryName" : "AUS" } ] }
Following is the query to find property of first element of array −
> db.firstElementOfArray.find({},{'Details':{$slice:1},'Details.CustomerName':1}).pretty();
This will produce the following output −
{ "_id" : 100, "Details" : [ { "CustomerName" : "John" } ] } { "_id" : 101, "Details" : [ { "CustomerName" : "Carol" } ] }
Advertisements