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" } ] }


你可能感兴趣的:(DB)