How to select a single field for all documents in a MongoDB collection?

前端 未结 20 1694
执念已碎
执念已碎 2020-11-22 07:58

In my MongoDB, I have a student collection with 10 records having fields name and roll. One record of this collection is:

{
    \"         


        
20条回答
  •  清歌不尽
    2020-11-22 08:29

    While gowtham's answer is complete, it is worth noting that those commands may differ from on API to another (for those not using mongo's shell).
    Please refer to documentation link for detailed info.

    Nodejs, for instance, have a method called `projection that you would append to your find function in order to project.

    Following the same example set, commands like the following can be used with Node:

    db.student.find({}).project({roll:1})

    SELECT _id, roll FROM student

    Or
    db.student.find({}).project({roll:1, _id: 0})

    SELECT roll FROM student

    and so on.

    Again for nodejs users, do not forget (what you should already be familiar with if you used this API before) to use toArray in order to append your .then command.

提交回复
热议问题