
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
Get Single Element from Array by Index in MongoDB
To get a single element, use aggregation and LIMIT. The skip() is used to skip a specific number of documents.
Let us first create a collection with documents −
> db.demo391.insertOne( ... { "_id" : 101, "Name" : "Chris", Values: ["101", "102"] } ... ) { "acknowledged" : true, "insertedId" : 101 } > db.demo391.insertOne( ... { "_id" : 111, "Name" : "Chris", Values: ["101", "102"] } ... ) { "acknowledged" : true, "insertedId" : 111 } > db.demo391.insertOne( ... { "_id" : 121, "Name" : "Chris", Values: ["101", "102"] } ... ) { "acknowledged" : true, "insertedId" : 121 }
Display all documents from a collection with the help of find() method −
> db.demo391.find();
This will produce the following output −
{ "_id" : 101, "Name" : "Chris", "Values" : [ "101", "102" ] } { "_id" : 111, "Name" : "Chris", "Values" : [ "101", "102" ] } { "_id" : 121, "Name" : "Chris", "Values" : [ "101", "102" ] }
Following is the query to get a single element from the array of results by index −
> var i=2; > db.demo391.aggregate([ ... { $match : {"Name": "Chris"}}, ... { $skip : i-1}, ... { $limit : 1 } ... ]);
This will produce the following output −
{ "_id" : 111, "Name" : "Chris", "Values" : [ "101", "102" ] }
Advertisements