- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Aggregate a $slice to get an element in exact position from a nested array in MongoDB?
You can use aggregate framework for this. Let us first create a collection with documents −
>db.exactPositionDemo.insertOne({"StudentName":"John","StudentScores":[78,98,56,45,89]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd29a1c345990cee87fd883") }
Following is the query to display all documents from a collection with the help of find() method −
> db.exactPositionDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd29a1c345990cee87fd883"), "StudentName" : "John", "StudentScores" : [ 78, 98, 56, 45, 89 ] }
Case 1 − Query to aggregate a $slice to get an element in exact position with 0,1 −
> db.exactPositionDemo.aggregate([ { "$project": { "StudentScores": { "$slice": ["$StudentScores",0,1] } }} ]);
This will produce the following output −
{ "_id" : ObjectId("5cd29a1c345990cee87fd883"), "StudentScores" : [ 78 ] }
Case 2 − Query to aggregate a $slice to get an element in exact position with 1,1 −
> db.exactPositionDemo.aggregate([ { "$project": { "StudentScores": { "$slice": ["$StudentScores",1,1] } }} ]);
This will produce the following output −
{ "_id" : ObjectId("5cd29a1c345990cee87fd883"), "StudentScores" : [ 98 ] }
Advertisements