Get a single element from the array of results by index in MongoDB

MongoDBDatabaseBig Data Analytics

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" ] }
raja
Published on 02-Apr-2020 17:40:32
Advertisements