1. 程式人生 > >spring boot+mongodb入門隨筆02 join操作$lookup

spring boot+mongodb入門隨筆02 join操作$lookup

目的是要實現類似sql的join操作 參考$lookup

public class OrderQsDemographicSize {
	@Id
	private String id;
	private String demographic;
	private List<String> sizes;
	private ObjectId userId;
	private String realname;//這個時用來lookup(join)的	
......getter setter......
public class User {
	@Id
	private String id;
	private String name;	
	@Field("pass")
	private String password;
	private String realname;	

要實現sql=select s.*,u.realname from orderQsDemographicSize s left join user u on u.id=s.userId 功能

	@Autowired
	MongoTemplate MongoTemplate;
......
       //設定lookup
	   LookupOperation lookupOperation = LookupOperation.newLookup().from("user").localField("userId")
				.foreignField("_id").as("userDoc");
     //這裡分兩個部分,先lookup,結果再用project篩選,如果不篩選user裡面所有內容,包括密碼都會輸出
		Aggregation aggregation = newAggregation(lookupOperation,project("id", "demographic", "sizes", "userDoc.realname"));

		///////////////////
		logger.debug(aggregation.toString());//看具體的查詢,有助於理解各個引數的影響
		//////
		//正式查詢		
		List<OrderQsDemographicSize> list = MongoTemplate
				.aggregate(aggregation, "orderQsDemographicSize", OrderQsDemographicSize.class).getMappedResults();
				

由於mongo可多級擴充套件的特性,需要join的操作實際上大大減少了,然而多個表共用的資料還是難免需要join。雖然要多寫幾行程式碼,用熟了也不覺得麻煩。