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
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" ] }Advertisements