MongoDB 連接查詢 $lookup

MongoDB 在 2015年發佈的新版本 V3.2 中支持了 左外連接 的查詢方法, 官方文檔如下:



****

Lookup

Starting in 3.2, MongoDB provides a new $lookup pipeline stage that performs a left outer join with another collection to filter in documents from the joined collection for processing.

This example performs a left outer join on the fromCollection collection, joining the local field to thefrom field and outputted in the joinedOutput field:

lookup("fromCollection", "local", "from", "joinedOutput")

****



該方法包含四個參數,  

fromCollection => 需要連接的Collection

local => 當前Collection中需要連接的字段

from => 外連Collection中連接查詢的字段

joinedOutput => 查詢結果輸出到此字段中


BUT!  在使用的過程中,該函數會報此錯誤:

Exception in thread "main" com.mongodb.MongoQueryException: Query failed with error code 2 and error message 'unknown top level operator: $lookup' on server 127.0.0.1:27017

未知的 $lookup 操作符,坑爹的 MongoDB , 此功能只有 Enterprise 版本的纔可使用,意思是你要用此功能需掏錢,我一口老血噴在了鍵盤上...


當然一個正確的查詢實例是什麼樣呢?


db.left.find()
{ "_id" : ObjectId("56b0ea87e64ac61fa9b36b2b"), "name" : "Rod", "ref" : 1 }
{ "_id" : ObjectId("56b0ea87e64ac61fa9b36b2c"), "name" : "Jane", "ref" : 1 }
{ "_id" : ObjectId("56b0ea87e64ac61fa9b36b2d"), "name" : "Freddy", "ref" : 2 }

db.right.find()
{ "_id" : 1, "rightData" : "One" }
{ "_id" : 2, "rightData" : "Two" }

db.left.aggregate(
[{
	$lookup:
	{
		from: "right",
		localField:	"ref",
		foreignField: "_id", 
		as: "stuffFromRight" 
	}}])
{ "_id" : ObjectId("56b0ea87e64ac61fa9b36b2b"), "name" : "Rod", "ref" : 1, "stuffFromRight" : [ { "_id" : 1, "rightData" : "One" } ] }
{ "_id" : ObjectId("56b0ea87e64ac61fa9b36b2c"), "name" : "Jane", "ref" : 1, "stuffFromRight" : [ { "_id" : 1, "rightData" : "One" } ] }
{ "_id" : ObjectId("56b0ea87e64ac61fa9b36b2d"), "name" : "Freddy", "ref" : 2, "stuffFromRight" : [ { "_id" : 2, "rightData" : "Two" } ] }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章