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


等效语法如下。

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() 方法显示集合中的所有文档。查询如下所示 -

> 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 数据库中 select column1, column2 from tbl 的等效语法 -

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

更新于: 30-Jul-2019

190 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告