问题:mongodb 查询可以用别名吗?mysql 查询可以这样写:select student_name as sname from tablesname 是字段 student_name 的别名那么,强大的mongodb有别名的用法吗?网上没有查到,向大家求助
3 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
可以使用别名,不过要用
aggregate()进行查询,并且,要把需要显示的名称全部列出来
你要将需要显示的列,全部写在
$project中
db.getCollection('discerns').aggregate([ { $project: { 'date': '$DateTime' } } ]);
如果要起别名,对象的键就是别名,值就是实际的数据库字段名(字段名要用$符号开头,否则 mongodb 会将其解析为一个字符串)
_id会默认查询出来,如果不想要 _id 查询出来,需要手动设置 _id:0
除 _id外,其他字段值不设置,则不会查询出来
长风秋雁
TA贡献1757条经验 获得超7个赞
可以的,将投射过的字段在结果中重命名:
原始数据:
> 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" }
- 3 回答
- 0 关注
- 5926 浏览
添加回答
举报
0/150
提交
取消