在MySQL中,我们为列指定别名。同样,您可以在MongoDB中为字段名称提供别名。MongoDB的等效语法如下
db.yourCollectionName.aggregate( [ { "$project": { "_id": 0, "anyAliasName": "$yourFieldName" }} ]);
首先让我们创建一个包含文档的集合
> db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d448827b86948e204ca91") } > db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d449027b86948e204ca92") } > db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d449527b86948e204ca93") } > db.selectFieldAsAnotherNameDemo.insertOne({"Name":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9d449927b86948e204ca94") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.selectFieldAsAnotherNameDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9d448827b86948e204ca91"), "Name" : "Larry" } { "_id" : ObjectId("5c9d449027b86948e204ca92"), "Name" : "Robert" } { "_id" : ObjectId("5c9d449527b86948e204ca93"), "Name" : "Sam" } { "_id" : ObjectId("5c9d449927b86948e204ca94"), "Name" : "Mike" }
以下是对与SELECT字段AS`anothername`相对应的MongoDB的查询
> db.selectFieldAsAnotherNameDemo.aggregate( ... [ ... { "$project": { ... "_id": 0, ... "StudentName": "$Name" ... }} ... ]);
这将产生以下输出
{ "StudentName" : "Larry" } { "StudentName" : "Robert" } { "StudentName" : "Sam" } { "StudentName" : "Mike" }