创建表的时候没有设置id使用mongodb自定义的id,之后查数据获取不到数据
表结构
使用默认id
查询为空,之后发现mongodb默认生成的ID是Object Id
{"_id":“60e542d1e8f6375134a6c0d3”} 修改成 {"_id":ObjectId(“60e542d1e8f6375134a6c0d3”)} 查询成功
多表联查
UmsRole表 id不为mongodb默认id
UmsAdminRolr表
collection_user 默认 id查询为空 umsRole自定义id可以查询到数据
之后想着可不可以吧forerignField设置成ObjectId 于是报错
之后查看了是mongodb3.20版本不支持 $ lookup与ObjectId匹配
之后去官网查了下 看到了这个方法,吧ObjectId。str转成String ,之后发现也不可以
https://jira.mongodb.org/browse/SERVER-22781?jql=text%20~%20%22%24lookup%20objectID%22
之后解决方法
把OBjectId类型全部换成赋值id,String ,Integer 都可以,
修改中间表的字段,不用Id去关联,我这有个username也是唯一的所以就去用了这个来连表,
最好使用的方法就是创建表的时候不要使用mongodb自带的id来
java实现 返回map好接收
@Override
public List<Map> findUmsAdminRoleLIsts() {
// TODO Auto-generated method stub
Aggregation aggregation = Aggregation.newAggregation(
// 要连接的表名 当前表对对应的字段 要连接表中的字段 查询结果中显示的字段
Aggregation.lookup("UmsRole", "umsRole_id", "_id", "umsRolelist"),
Aggregation.lookup("collection_user", "userEntity_userName", "userVo.userName", "userEntitylist")
// Aggregation.unwind("userEntity"),
// Aggregation.group("userEntity._id").first("userEntity.name").as("UserEntity.name")
);
System.out.println(aggregation);
List<Map> list = mongoTemplate.aggregate(aggregation, UmsAdminRoleRelation.class, Map.class).getMappedResults();
return list;
}
postman测试调用返回 获取成功
https://blog.csdn.net/qq_31868149/article/details/82912139
这个是将Aggregation-聚合查询里面的一些参数,和mysql的对比
where ( m a t c h ) 、 g r o u p b y ( match) 、group by ( match)、groupby(group) 、select( p r o j e c t ) 、 o r d e r b y ( project)、order by( project)、orderby(sort)、limit( l i m i t ) s u m ( limit) sum( limit)sum(sum)、count( s u m ) 、 j o i n ( sum)、join( sum)、join(lookup)
就查出了我自己的
Aggregation aggregation = Aggregation.newAggregation(
// 要连接的表名 当前表对对应的字段 要连接表中的字段 查询结果中显示的字段
Aggregation.lookup("UmsRole", "umsRole_id", "_id", "umsRolelist"),
Aggregation.lookup("collection_user", "userEntity_userName", "userVo.userName", "userEntitylist"),
Aggregation.match(Criteria.where("userEntity_userName").is("sq"))
);