

- 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
MongoDB query to slice only one element of array
To slice only one element of array, use $slice in MongoDB. Let us create a collection with documents −
> db.demo579.insertOne( ... { ... "_id" : 101, ... "details" : { "FirstName" : "John" }, ... "Marks" : [ 56,78,90,34,45,74 ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo579.find().pretty();
This will produce the following output −
{ "_id" : 101, "details" : { "FirstName" : "John" }, "Marks" : [ 56, 78, 90, 34, 45, 74 ] }
Following is the query to slice only one the element of the array −
> db.demo579.find({},{Marks : {$slice : 1} ,"details":0,"_id":0})
This will produce the following output −
{ "Marks" : [ 56 ] }
- Related Questions & Answers
- How to use $slice operator to get last element of array in MongoDB?
- MongoDB Aggregation to slice array inside array
- MongoDB query to find property of first element of array?
- MongoDB query to get average in aggregation of array element?
- MongoDB slice array in populated field?
- MongoDB aggregate $slice to get the length of the array
- MongoDB query to count the frequency of every element of the array
- MongoDB query to pull array element from a collection?
- MongoDB query to add new array element in document
- MongoDB query on nth element (variable index) of subdocument array
- MongoDB query to get only specific fields in nested array documents?
- MongoDB query to return only embedded document?
- MongoDB query to get only distinct values
- MongoDB query to update only certain fields?
- Remove only one document in MongoDB?
Advertisements