赞
踩
最近在看同事代码的时候,注意到了$lookup
多表关联查询,不太清楚类比MySQL中是哪种连接查询,因此就有了此次的测试总结。接下来,我会用测试结果来介绍MySQL中的内连接、左外连接、右外连接,介绍MongoDB中$lookup的用法以及进行测试,最后通过测试结果来得出类比结果。
MySQL中的连接分为内连接、左外连接、右外连接。
首先,我们先准备好测试数据:
接下来,通过测试结果来说明各种不同连接之间的不同结果集。
内连接(INNER JOIN):获取两个表中字段匹配关系的记录。
左外连接(LEFT JOIN):获取左表所有记录,如果右表没有匹配的记录,就会用NULL来填充。
右外连接(RIGHT JOIN):获取右表所有记录,如果左表没有匹配的记录,就会用NULL来填充。
db.author.aggregate([
{
$lookup: {
from: "book",
localField: "author_name",
foreignField: "book_author",
as: "author_book"
}
}
])
参数说明:
from:需要连接的集合
localField:在输入文档中的查找字段
foreignField:需要在from集合中查找的字段
as:输出字段的名字
查询结果:
{ "_id" : ObjectId("5f35f353522322825c20f46d"), "author_id" : "1", "author_name" : "吴承恩", "author_sex" : "男", "dynasty" : "明代", "author_book" : [ { "_id" : ObjectId("5f35f2ea386df5178044cc2b"), "book_id" : "4", "book_name" : "西游记", "book_author" : "吴承恩", "book_desc" : "孙悟空、唐僧" } ] }
{ "_id" : ObjectId("5f35f3b0386df5178044cc2d"), "author_id" : "2", "author_name" : "曹雪芹", "author_sex" : "男", "dynasty" : "清代", "author_book" : [ { "_id" : ObjectId("5f35f1b4522322825c20f46c"), "book_id" : "1", "book_name" : "红楼梦", "book_author" : "曹雪芹", "book_desc" : "贾宝玉、林黛玉" } ] }
{ "_id" : ObjectId("5f35f489386df5178044cc2e"), "author_id" : "3", "author_name" : "罗贯中", "author_sex" : "男", "dynasty" : "元末", "author_book" : [ { "_id" : ObjectId("5f35f28b386df5178044cc29"), "book_id" : "2", "book_name" : "三国演义", "book_author" : "罗贯中", "book_desc" : "魏、蜀汉、吴" } ] }
{ "_id" : ObjectId("5f35f489386df5178044cc2f"), "author_id" : "4", "author_name" : "施耐庵", "author_sex" : "男", "dynasty" : "北宋", "author_book" : [ { "_id" : ObjectId("5f35f2d1386df5178044cc2a"), "book_id" : "3", "book_name" : "水浒传", "book_author" : "施耐庵", "book_desc" : "梁山英雄" } ] }
{ "_id" : ObjectId("5f35f489386df5178044cc30"), "author_id" : "5", "author_name" : "朱自清", "author_sex" : "男", "dynasty" : "现代", "author_book" : [ ] }
{ "_id" : ObjectId("5f35f489386df5178044cc31"), "author_id" : "6", "author_name" : "鲁迅", "author_sex" : "男", "dynasty" : "现代", "author_book" : [ ] }
通过对比上述测试结果,我们可以得出结论:MongoDB中的$lookup得到的多表关联查询可以类比MySQL中的左连接。
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。