问题:MongoDB查询可以用别名吗?
mysql 查询可以这样写:
select student_name as sname from table
sname 是字段 student_name 的别名
那么,强大的MongoDB有别名的用法吗?网上没有查到,向大家求助
本问题及下方已被采纳的回答均来自云栖社区【Redis&MongoDB 社区大群】。https://yq.aliyun.com/articles/690084 点击链接欢迎加入社区大社群。
可以的,将投射过的字段在结果中重命名:
原始数据:
db.zipcode.find()
{ "_id" : "01001", "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338, "state" : "MA" }
{ "_id" : "01002", "city" : "AGAWAM", "loc" : [ -72.51565, 42.377017 ], "pop" : 36963, "state" : "MA" }
{ "_id" : "01005", "city" : "AGAWAM", "loc" : [ -72.108354, 42.409698 ], "pop" : 4546, "state" : "MA" }
{ "_id" : "01007", "city" : "BELCHERTOWN", "loc" : [ -72.410953, 42.275103 ], "pop" : 10579, "state" : "MA" }
{ "_id" : "01008", "city" : "BLANDFORD", "loc" : [ -72.936114, 42.182949 ], "pop" : 1240, "state" : "MA" }
显示原字段和重命名字段名称:
db.zipcode.aggregate({$project:{myid:"$_id"}})
{ "_id" : "01001", "myid" : "01001" }
{ "_id" : "01002", "myid" : "01002" }
{ "_id" : "01005", "myid" : "01005" }
{ "_id" : "01007", "myid" : "01007" }
{ "_id" : "01008", "myid" : "01008" }
只显示重命名字段名称:
db.zipcode.aggregate({$project:{myid:"$_id",_id:0}})
{ "myid" : "01001" }
{ "myid" : "01002" }
{ "myid" : "01005" }
{ "myid" : "01007" }
{ "myid" : "01008" }
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。