MongoDB - how can I access fields in a document?



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" }
Updated on: 2020-05-14T08:31:37+05:30

388 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements