您可以使用聚合框架创建别名。首先让我们创建一个包含文档的集合-
> db.creatingAliasDemo.insertOne({_id:101,"Name":"John Doe"}); { "acknowledged" : true, "insertedId" : 101 } > db.creatingAliasDemo.insertOne({_id:102,"Name":"David Miller"}); { "acknowledged" : true, "insertedId" : 102 } > db.creatingAliasDemo.insertOne({_id:103,"Name":"Sam Williams"}); { "acknowledged" : true, "insertedId" : 103 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.creatingAliasDemo.find().pretty();
这将产生以下输出-
{ "_id" : 101, "Name" : "John Doe" } { "_id" : 102, "Name" : "David Miller" } { "_id" : 103, "Name" : "Sam Williams" }
以下是在查询中创建别名的查询-
> db.creatingAliasDemo.aggregate( ... [ ... { ... $project: { ... _id:1, ... "FullName":"$Name" ... } ... } ... ] ... );
这将产生以下输出-
{ "_id" : 101, "FullName" : "John Doe" } { "_id" : 102, "FullName" : "David Miller" } { "_id" : 103, "FullName" : "Sam Williams" }