MongoDB - how can I access fields in a document?

MongoDBDatabaseBig Data Analytics

To access fields in a document, simply use find(). Let us create a collection with documents −

> db.demo565.insertOne(
... {
...    id:101,
...    Name:"David",
...    "CountryName":"US"
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e90896739cfeaaf0b97b577")
}
>
> db.demo565.insertOne(
... {
...    id:102,
...    Name:"Carol",
...    "CountryName":"UK"
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e90896839cfeaaf0b97b578")
}
>
> db.demo565.insertOne(
... {
...    id:103,
...    Name:"Sam",
...    "CountryName":"AUS"
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e90896839cfeaaf0b97b579")
}

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

> db.demo565.find();

This will produce the following output −

{ "_id" : ObjectId("5e90896739cfeaaf0b97b577"), "id" : 101, "Name" : "David", "CountryName" : "US" }
{ "_id" : ObjectId("5e90896839cfeaaf0b97b578"), "id" : 102, "Name" : "Carol", "CountryName" : "UK" }
{ "_id" : ObjectId("5e90896839cfeaaf0b97b579"), "id" : 103, "Name" : "Sam", "CountryName" : "AUS" }

Following is the query to access fields −

> db.demo565.find({"Name":"Carol",CountryName:"UK"},{Name:1});

This will produce the following output −

{ "_id" : ObjectId("5e90896839cfeaaf0b97b578"), "Name" : "Carol" }
raja
Published on 14-May-2020 12:00:57
Advertisements