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


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值