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