如何从MongoDB数据库中的tbl中获取SELECT column1,column2的等效项?

等效语法如下。

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

为了理解上述语法,让我们用文档创建一个集合。使用文档创建集合的查询如下-

> 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")
}

find()method的帮助下显示集合中的所有文档。查询如下-

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

以下是输出-

{
   "_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"
}

这是MongoDB数据库中tbl的select column1,column2的等效语法-

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

以下是输出-

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

如果您不想包含_id,请使用以下查询-

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

以下是输出-

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