View just certain fields from a documents

I found this site : MongoDB query select and display only a specific field from the document?
and my question was how to view just certain fields from a documents. The particular statement is
db.querySelectDemo.find().pretty(); However there are some problems
#1. Collection is not mentioned
#2. with Mongosh from Compass, I dont see querySelectDemo - so smells like a private function
Any ideas ?
Thanks !

Hi @Andrew_Watts
Welcome to the community forum!!

is represented using the format:
db.<collection-name>.find().pretty() where find() and pretty() are built-in functions to find all the documents and to display the documents in a formatted pattern respectively.

Could you please confirm the following information from Compass:

  1. Are you on the right database where the collection is created?
  2. If yes for #1, is the collection created for the database you are using?
  3. The insert command mentioned in the MongoDB query select and display only a specific field from the document? documentation been used for the respective collection.

To answer this, there could be multiple ways to view only selected fields from the collection.

  1. As mentioned in the document:

    db.querySelectDemo.find({},{_id:0,UserName:true});

  2. Using $project with db.<collection-name>.aggregate( [ { $project : { _id : 0 , UserName : 1 } } ] )
    where 0 represents field exclusion and 1 represents field inclusion.

Thanks
Aasawari

2 Likes

Thanks for you explanation - I did not explain clearly.
The compass version is 1.31.2 / mongash works fine. I was puzzled how the tutorlal website could grab the collection without it being identified - there’s lots I dont know but I thought either they werent using MongoDb or theses some private function in use. Thanks for showing me how the capability to view specific values of a document collection would work !

Oh, I see now, the querypoing tutorial name the coillection querySelectDemo - how confusing !

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.