Tutorialspoint

1 Answer
Anvi Jain

Yes, you can use the findOne(). Following is the syntax −

db.yourCollectionName.findOne();

You can use toArray() as well −

db.yourCollectionName.find().toArray();

Let us first create a collection with documents −

> db.betterFormatDemo.insertOne({"StudentName":"Adam Smith","StudentScores":[98,67,89]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ab826d78f205348bc640")
}
> db.betterFormatDemo.insertOne({"StudentName":"John Doe","StudentScores":[67,89,56]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7ab936d78f205348bc641")
}
> db.betterFormatDemo.insertOne({"StudentName":"Sam Williams","StudentScores":[45,43,33]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd7aba76d78f205348bc642")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.betterFormatDemo.find();

This will produce the following output −

{ "_id" : ObjectId("5cd7ab826d78f205348bc640"), "StudentName" : "Adam Smith", "StudentScores" : [ 98, 67, 89 ] }
{ "_id" : ObjectId("5cd7ab936d78f205348bc641"), "StudentName" : "John Doe", "StudentScores" : [ 67, 89, 56 ] }
{ "_id" : ObjectId("5cd7aba76d78f205348bc642"), "StudentName" : "Sam Williams", "StudentScores" : [ 45, 43, 33 ] }

Case 1 − Using findOne().

Following is the query to display the MongoDB results in a better format −

> db.betterFormatDemo.findOne();

This will produce the following output −

{
   "_id" : ObjectId("5cd7ab826d78f205348bc640"),
   "StudentName" : "Adam Smith",
   "StudentScores" : [
      98,
      67,
      89
   ]
}

Case 2 − Using find().toArray().

Following is the query to display the MongoDB results in a better format −

> db.betterFormatDemo.find().toArray();

This will produce the following output −

[
   {
      "_id" : ObjectId("5cd7ab826d78f205348bc640"),
      "StudentName" : "Adam Smith",
      "StudentScores" : [
         98,
         67,
         89
      ]
   },
   {
      "_id" : ObjectId("5cd7ab936d78f205348bc641"),
      "StudentName" : "John Doe",
      "StudentScores" : [
         67,
         89,
         56
      ]
   },
   {
      "_id" : ObjectId("5cd7aba76d78f205348bc642"),
      "StudentName" : "Sam Williams",
      "StudentScores" : [
         45,
         43,
         33
      ]
   }
]

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.