Retrieve data from a MongoDB collection?

MongoDBDatabaseBig Data Analytics

To return a single document from a collection, use findOne() in MongoDB. Let us create a collection with documents −

> db.demo463.insertOne({"StudentName":"Chris
Brown","StudentAge":21,"StudentCountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ec8cb66ccba22cc9dcf")
}
> db.demo463.insertOne({"StudentName":"David
Miller","StudentAge":23,"StudentCountryName":"UK"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ed5cb66ccba22cc9dd0")
}
> db.demo463.insertOne({"StudentName":"John
Doe","StudentAge":22,"StudentCountryName":"AUS"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7ee1cb66ccba22cc9dd1")
}
> db.demo463.insertOne({"StudentName":"John
Smith","StudentAge":24,"StudentCountryName":"US"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7f7eefcb66ccba22cc9dd2")
}

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

> db.demo463.find();

This will produce the following output −

{ "_id" : ObjectId("5e7f7ec8cb66ccba22cc9dcf"), "StudentName" : "Chris Brown",
"StudentAge" : 21, "StudentCountryName" : "US" }
{ "_id" : ObjectId("5e7f7ed5cb66ccba22cc9dd0"), "StudentName" : "David Miller",
"StudentAge" : 23, "StudentCountryName" : "UK" }
{ "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"), "StudentName" : "John Doe", "StudentAge" :
22, "StudentCountryName" : "AUS" }
{ "_id" : ObjectId("5e7f7eefcb66ccba22cc9dd2"), "StudentName" : "John Smith", "StudentAge"
: 24, "StudentCountryName" : "US" }

Following is the query to retrieve data from MongoDB −

> db.demo463.findOne({"StudentName":"John Doe"});

This will produce the following output −

{
   "_id" : ObjectId("5e7f7ee1cb66ccba22cc9dd1"),
   "StudentName" : "John Doe",
   "StudentAge" : 22,
   "StudentCountryName" : "AUS"
}
raja
Published on 11-May-2020 09:29:08
Advertisements