

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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" } ] }
- Related Questions & Answers
- MongoDB query to remove element from array as sub property
- MongoDB query to slice only one element of array
- MongoDB query to get average in aggregation of array element?
- MongoDB query to count the frequency of every element of the array
- MongoDB query on nth element (variable index) of subdocument array
- MongoDB query to find multiple matchings inside array of objects?
- Projection of arrays to get the first array element from MongoDB documents
- Query array of subdocuments in MongoDB
- MongoDB query to pull array element from a collection?
- MongoDB query to add new array element in document
- Match element in array of MongoDB?
- Find the first repeating element in an array of integers C++
- MongoDB query to get array of nested string?
- MongoDB query to change order of array elements?
- MongoDB query check if value in array property?
Advertisements