Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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" }Advertisements