Syntax error Querying only the field name and display only the id in MongoDB?

Querying only the field name and display only the id in MongoDB?



To query only the field name, set fieldName to 0 i.e. the fieldName to hide. Let us create a collection with documents −

> db.demo650.insertOne({_id:101,details:{Name:"Chris",Age:21}});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo650.insertOne({_id:102,details:{Name:"Bob",Age:22}});
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo650.insertOne({_id:103,details:{Name:"Sam",Age:20}});
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo650.insertOne({_id:104,details:{Name:"Robert",Age:24}});
{ "acknowledged" : true, "insertedId" : 104 }

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

> db.demo650.find();

This will produce the following output −

{ "_id" : 101, "details" : { "Name" : "Chris", "Age" : 21 } }
{ "_id" : 102, "details" : { "Name" : "Bob", "Age" : 22 } }
{ "_id" : 103, "details" : { "Name" : "Sam", "Age" : 20 } }
{ "_id" : 104, "details" : { "Name" : "Robert", "Age" : 24 } }

Following is how to query only the field name in MongoDB. We wanted to hide details field, therefore we have set it to 0 −

> db.demo650.find({},{details:0});

This will produce the following output −

{ "_id" : 101 }
{ "_id" : 102 }
{ "_id" : 103 }
{ "_id" : 104 }
Updated on: 2020-05-12T08:57:02+05:30

873 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements