- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
MongoDB slice array in populated field?
To slice array, use a $slice operator in MongoDB. Let us create a collection with documents −
> db.demo503.insertOne({_id:1,Name:"John",Subject:["MySQL","Java","C"]}); { "acknowledged" : true, "insertedId" : 1 } > db.demo503.insertOne({_id:2,Name:"David",Subject:["MongoDB","C++","Python"]}); { "acknowledged" : true, "insertedId" : 2 }
Display all documents from a collection with the help of find() method −
> db.demo503.find().pretty();
This will produce the following output −
{ "_id" : 1, "Name" : "John", "Subject" : [ "MySQL", "Java", "C" ] } { "_id" : 2, "Name" : "David", "Subject" : [ "MongoDB", "C++", "Python" ] }
Following is the query to slice array in the populated field −
> db.demo503.find({_id:2}, { 'Subject': { $slice: -1 }});
This will produce the following output −
{ "_id" : 2, "Name" : "David", "Subject" : [ "Python" ] }
- Related Articles
- MongoDB Aggregation to slice array inside array
- Reverse array field in MongoDB?
- MongoDB query to slice only one element of array
- MongoDB aggregate $slice to get the length of the array
- Array slice() in JavaScript
- Update field in exact element array in MongoDB?
- How to use $slice operator to get last element of array in MongoDB?
- JavaScript Array slice()
- Project specific array field in a MongoDB collection?
- Get distinct levels of array field in MongoDB?
- Push and slice multiple times in MongoDB?
- Array slice function in Ruby
- Replace an array field value with MongoDB?
- Delete all elements in an array field in MongoDB?
- Set MongoDB $slice with a range?

Advertisements