Fetch specific documents with array values in MongoD

MongoDBDatabaseBig Data Analytics

To fetch specific documents, use limit() along with toArray(). The toArray() method returns an array that contains all the documents from a cursor. Let us create a collection with documents −

> db.demo482.insertOne({_id:1,"StudentInformation":[{"Name":"Chris","Age":21}]});
{ "acknowledged" : true, "insertedId" : 1 }
> db.demo482.insertOne({_id:2,"StudentInformation":[{"Name":"Bob","Age":23}]});
{ "acknowledged" : true, "insertedId" : 2 }
> db.demo482.insertOne({_id:3,"StudentInformation":[{"Name":"David","Age":20}]});
{ "acknowledged" : true, "insertedId" : 3 }

Display all documents from a collection with the help of find() method −

> db.demo482.find();

This will produce the following output −

{ "_id" : 1, "StudentInformation" : [ { "Name" : "Chris", "Age" : 21 } ] }
{ "_id" : 2, "StudentInformation" : [ { "Name" : "Bob", "Age" : 23 } ] }
{ "_id" : 3, "StudentInformation" : [ { "Name" : "David", "Age" : 20 } ] }

Following is the query to fetch specific documents with limit() −

> db.demo482.find({}).limit(2).toArray();

This will produce the following output −

[
   {
      "_id" : 1,
      "StudentInformation" : [
         {
            "Name" : "Chris",
            "Age" : 21
         }
      ]
   },
   {
      "_id" : 2,
      "StudentInformation" : [
         {
            "Name" : "Bob",
            "Age" : 23
         }
      ]
   }
]
raja
Published on 11-May-2020 09:54:49
Advertisements