赞
踩
我使用的是spring包里的mongoTemplate进行操作Mongo,那基本单表的操作满足日常需求了;但是难免会有要联表操作的时候,mongo-data包里提供了一种Aggregation
类,可以理解为建立管道。
LookupOperation
这个类就是用来进行联表操作的类,具体方法:
// 联表
LookupOperation lookupOperation = LookupOperation.newLookup()
// 连接哪张表
.from("Item")
// 主表哪个字段连接
.localField("sItemId")
// 从表哪个字段关联
.foreignField("_id")
// 从表结果集名 最后会在主表多出这个自定义列 默认List
.as("item");
ProjectionOperation
这个类可以理解为构造Mysql的Select列
// 类似mysql的select列 如果要用从表的列 就as自定义列名点属性
ProjectionOperation projectionOperation = Aggregation.project("id", "sItemId", "iCount", "item.iDuration", "item.sName", "item.sIcon", "item.sDes", "item.iItemType");
Item
{ "_id": "111", "sActiveId": "222", "sName": "333", "sIcon": "444", "sDes": "555", "iItemType": NumberInt("1"), "sValue": "666", "iProperty": [ "0" ], "iDuration": NumberInt("77"), "createTime": ISODate("2022-03-23T08:13:19.694Z"), "updateTime": ISODate("2022-03-23T08:13:19.694Z"), "iStatus": NumberInt("0") }
ItemUser
{
"_id": "222",
"sActiveId": "333",
"sItemId": "111",
"sUserId": "444",
"iCount": NumberInt("4")
}
// 联表 LookupOperation lookupOperation = LookupOperation.newLookup() // 连接哪张表 .from("Item") // 主表哪个字段连接 .localField("sItemId") // 从表哪个字段关联 .foreignField("_id") // 从表结果集名 最后会在主表多出这个自定义列 默认List .as("item"); // 查询 Criteria criteria = Criteria.where("sUserId").is("444"); // 类似mysql的select列 如果要用从表的列 就as自定义列名点属性 ProjectionOperation projectionOperation = Aggregation.project("id", "sItemId", "iCount", "item.iDuration", "item.sName", "item.sIcon", "item.sDes", "item.iItemType"); // 建立管道 Aggregation aggregation = Aggregation.newAggregation( // 联表 lookupOperation, // 查询 Aggregation.match(criteria), // 将某个集合列拆成字段添加主表 Aggregation.unwind("item"), // 排序 Aggregation.sort(Sort.Direction.DESC, "createTime"), // select projectionOperation ); AggregationResults<JSONObject> aggregationResults = mongoTemplate.aggregate(aggregation, "ItemUser", JSONObject.class); List<JSONObject> result = aggregationResults.getMappedResults();
前面提到,as会在主表新增个列,列里内容是数组,Aggregation.unwind(“item”)的作用就是把as列里数组拆掉,通过ProjectionOperation 加在主表自定义字段中
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。