How to get the equivalent for SELECT column1, column2 FROM tbl in MongoDB Database?


The equivalent syntax is as follows.

db.yourCollectionName.find({}, {_id: 1, "column1": 1, "column2": 1}).pretty();

To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.equivalentForSelectColumn1Column2Demo.insertOne({"CustomerName":"John","CustomerAge":26,"CustomerCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92c6205259fcd19549980a")
}
> db.equivalentForSelectColumn1Column2Demo.insertOne({"CustomerName":"David","CustomerAge":22,"CustomerCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92c6305259fcd19549980b")
}
> db.equivalentForSelectColumn1Column2Demo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c92c6415259fcd19549980c")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.equivalentForSelectColumn1Column2Demo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c92c6205259fcd19549980a"),
   "CustomerName" : "John",
   "CustomerAge" : 26,
   "CustomerCountryName" : "US"
}
{
   "_id" : ObjectId("5c92c6305259fcd19549980b"),
   "CustomerName" : "David",
   "CustomerAge" : 22,
   "CustomerCountryName" : "AUS"
}
{
   "_id" : ObjectId("5c92c6415259fcd19549980c"),
   "CustomerName" : "Chris",
   "CustomerAge" : 24,
   "CustomerCountryName" : "UK"
}

Here is the equivalent syntax for select column1, column2 from tbl in MongoDB database −

> db.equivalentForSelectColumn1Column2Demo.find({}, {"CustomerName": 1, "CustomerAge": 1}).pretty();

The following is the output −

{
   "_id" : ObjectId("5c92c6205259fcd19549980a"),
   "CustomerName" : "John",
   "CustomerAge" : 26
}
{
   "_id" : ObjectId("5c92c6305259fcd19549980b"),
   "CustomerName" : "David",
   "CustomerAge" : 22
}
{
   "_id" : ObjectId("5c92c6415259fcd19549980c"),
   "CustomerName" : "Chris",
   "CustomerAge" : 24
}

If you do not want to include _id, use the below query −

> db.equivalentForSelectColumn1Column2Demo.find({}, {_id: 0, "CustomerName": 1, "CustomerAge": 1}).pretty();

The following is the output −

{ "CustomerName" : "John", "CustomerAge" : 26 }
{ "CustomerName" : "David", "CustomerAge" : 22 }
{ "CustomerName" : "Chris", "CustomerAge" : 24 }

Updated on: 30-Jul-2019

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements