

- 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
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 ] }
- Related Questions & Answers
- MongoDB aggregate $slice to get the length of the array
- MongoDB query to aggregate nested array
- Extract a particular element from a nested array in MongoDB
- How to remove an element from a doubly-nested array in a MongoDB document?
- Get the first element in an array and return using MongoDB Aggregate?
- MongoDB Aggregate Second Element from Input Element?
- How to get a particular element from MongoDB array?
- Update field in exact element array in MongoDB?
- How to use $slice operator to get last element of array in MongoDB?
- Extract particular element in MongoDB within a Nested Array?
- Removing an array element from a MongoDB collection
- MongoDB Aggregate to get average from document and of array elements?
- Unset an attribute from a single array element in MongoDB?
- MongoDB query to slice only one element of array
- Removing an element from a given position of the array in Javascript
Advertisements