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
Projection of arrays to get the first array element from MongoDB documents
If you want the first element from array, you can use $slice along with $gte. Let us create a collection with documents −
> db.demo640.insertOne({Name:"John","Scores":[80,90,75]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c2eb86c954c74be91e6e0")
}
> db.demo640.insertOne({Name:"Chris","Scores":[85,70,89]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9c2ece6c954c74be91e6e1")
}
Display all documents from a collection with the help of find() method −
> db.demo640.find();
This will produce the following output −
{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80, 90, 75 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85, 70, 89 ] }
Following is the query to projection of arrays using sing $slice −
> db.demo640.find({Scores:{$gte:85}},{ "Scores": {$slice : 1}});
This will produce the following output −
{ "_id" : ObjectId("5e9c2eb86c954c74be91e6e0"), "Name" : "John", "Scores" : [ 80 ] }
{ "_id" : ObjectId("5e9c2ece6c954c74be91e6e1"), "Name" : "Chris", "Scores" : [ 85 ] }Advertisements