

- 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
Getting only the first item for an array property in MongoDB?
Use $slice operator for this. Let us first create a collection with documents −
> db.gettingFirstItemInArrayDemo.insertOne( { "UserId": 101, "UserName":"Carol", "UserOtherDetails": [ {"UserFriendName":"Sam"}, {"UserFriendName":"Mike"}, {"UserFriendName":"David"}, {"UserFriendName":"Bob"} ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cdfca52bf3115999ed51205") }
Following is the query to display all documents from a collection with the help of find() method −
> db.gettingFirstItemInArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cdfca52bf3115999ed51205"), "UserId" : 101, "UserName" : "Carol", "UserOtherDetails" : [ { "UserFriendName" : "Sam" }, { "UserFriendName" : "Mike" }, { "UserFriendName" : "David" }, { "UserFriendName" : "Bob" } ] }
Following is the query to get only the first item for an array property in MongoDB −
> db.gettingFirstItemInArrayDemo.find({"UserId":101}, {UserOtherDetails:{$slice: 1}});
This will produce the following output −
{ "_id" : ObjectId("5cdfca52bf3115999ed51205"), "UserId" : 101, "UserName" : "Carol", "UserOtherDetails" : [ { "UserFriendName" : "Sam" } ] }
- Related Questions & Answers
- Search for documents matching first item in an array with MongoDB?
- Get the first and last item in an array using JavaScript?
- Removing item from array in MongoDB?
- Display only an element found in an array in MongoDB?
- MongoDB query to set a sub item in an array?
- How to update a MongoDB document for adding a new item to an array?
- How to move specific item in array list to the first item in Java?
- How to get only the first n% of an array in JavaScript?
- Can I get the first item in a Cursor object in MongoDB?
- MongoDB query to find property of first element of array?
- Retrieve only the queried element in an object array in MongoDB collection?
- How to insert an item to an array that is inside an object in MongoDB?
- Get the first element in an array and return using MongoDB Aggregate?
- MongoDB query to remove item from array?
- MongoDB query to gather unique array item?
Advertisements