MongoDB $lookup函数实现两个表的关联查询+筛选+取特定值

实现Mysql里inner join的效果

1、 两张表如下

db.getCollection('book');

db.getCollection("book").insert( {
    _id: ObjectId("5ec624b405ce835be78f258e"),
    channel: "fwpt",
    channelGoodsId: "30586",
    websiteId: NumberInt("1"),
    bookKinds: [
        "jd"
    ],
    bookState: NumberInt("1"),
    createTime: NumberLong("1590043829524"),
    goods: {
        channel: "fwpt",
        channelGoodsId: "30586",
        bookClass: "1",
        bookSubclass: "11",
        brandId: NumberInt("0"),
        brandName: "",
        choose: false,
        circulate: NumberInt("0"),
        courseType: "2",
        createStoreId: NumberInt("0"),
        createTime: "2020-05-21 11:53:09",
        electronBookId: "",
        goodsDetail: "",
        goodsKind: NumberInt("151"),
        goodsKindLevel: NumberInt("0"),
        goodsKindName: "",
        goodsMainPicUrl: "",
        goodsName: "四维阅读·茶馆",
        goodsPicUrls: "",
        goodsStates: NumberInt("1"),
        goodsSubject: "001",
        goodsTag: "",
        goodsTinyPicUrl: "",
        goodsType: NumberInt("1"),
        goodsTypeName: "",
        grades: [
            NumberInt("10")
        ],
        id: NumberInt("30586"),
        irreversible: false,
        marketPrice: 0,
        postFee: 0,
        pressName: "",
        publishType: NumberInt("0"),
        publisherId: NumberInt("127"),
        publisherName: "岳麓书社",
        qrCode: "",
        salePrice: 97.67,
        serviceTag: "",
        source: NumberInt("1"),
        status: "activity",
        stockHandle: "4",
        stockNumber: NumberInt("0"),
        storeDiscountRate: NumberInt("0"),
        storeGoodsStatus: NumberInt("0"),
        storeId: NumberInt("0"),
        storeOriginalPrice: NumberInt("0"),
        storePresent: false,
        storeSalePrice: NumberInt("0"),
        studyStage: "3;",
        subscriptionCode: "20200521060",
        supplierId: NumberInt("2"),
        supplierName: ""
    },
    wxMaQrCodeUrl: "https://res.xh-er.com/readingamuse/wxma_qrcode/20201126/1331884478359977984.jpg",
    book: {
        characterIntro: "",
        authorName: "老舍",
        authorIntro: "老舍(1899—1966),满族,原名舒庆春,字舍予。一生著作颇丰,在小说、诗歌、话剧创作及文艺理论方面均有建树。代表作有小说《老张的哲学》《骆驼祥子》《四世同堂》《离婚》《月牙儿》和剧本《茶馆》《龙须沟》等。\n",
        bookMainPicUrl: "https://res.xh-er.com/yuedou/book/bookMainPicUrl/2021/0106/160990221003008.jpg",
        briefIntro: "《茶馆》与《龙须沟》是当代中国话剧经典。《茶馆》以老北京一家裕泰茶馆的兴衰变迁为背景,向人们展现了近半个世纪的中国社会风云,昭示了中华民族在通往现代社会过程中所承受的坎坷而痛苦的命运。《龙须沟》以对比鲜明、真实质朴的手法,通过对居住于北京一条臭水沟旁的下层劳苦者新旧时代生活巨变的成功描写,为新社会高唱了一曲热情洋溢的颂歌。",
        authorPhoto: "",
        detailIntro: "<p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><strong><span style=\"font-family: 宋体;font-size: 14px\">1.ISBN:</span></strong><span style=\";font-family:宋体;font-size:14px\">978-7-5538-1</span><span style=\";font-family:宋体;font-size:14px\">445</span><span style=\";font-family:宋体;font-size:14px\">-</span><span style=\";font-family:宋体;font-size:14px\">2</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><span style=\";font-family:宋体;font-size:14px\">&nbsp;</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><strong><span style=\"font-family: 宋体;font-size: 14px\">2.书名:</span></strong><span style=\";font-family:宋体;font-size:14px\"><span style=\"font-family:宋体\">《</span></span><span style=\";font-family:宋体;font-size:14px\"><span style=\"font-family:宋体\">茶馆</span></span><span style=\";font-family:宋体;font-size:14px\"><span style=\"font-family:宋体\">》</span></span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><span style=\";font-family:宋体;font-size:14px\">&nbsp;</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><strong><span style=\"font-family: 宋体;font-size: 14px\">3.定价:</span></strong><span style=\";font-family:宋体;font-size:14px\">27.00元</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><span style=\";font-family:宋体;font-size:14px\">&nbsp;</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><strong><span style=\"font-family: 宋体;font-size: 14px\">4.版次:</span></strong><span style=\";font-family:宋体;font-size:14px\"><span style=\"font-family:宋体\">第</span>1版</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><span style=\";font-family:宋体;font-size:14px\">&nbsp;</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><strong><span style=\"font-family: 宋体;font-size: 14px\">5.出版时间:</span></strong><span style=\";font-family:宋体;font-size:14px\">202</span><span style=\";font-family:宋体;font-size:14px\">1</span><span style=\";font-family:宋体;font-size:14px\"><span style=\"font-family:宋体\">年</span></span><span style=\";font-family:宋体;font-size:14px\">1</span><span style=\";font-family:宋体;font-size:14px\"><span style=\"font-family:宋体\">月</span></span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><span style=\";font-family:宋体;font-size:14px\">&nbsp;</span></p><p style=\"text-autospace:ideograph-numeric;text-align:justify;text-justify:inter-ideograph;line-height:16px\"><strong><span style=\"font-family: 宋体;font-size: 14px\">6.出版社:</span></strong><span style=\";font-family:宋体;font-size:14px\"><span style=\"font-family:宋体\">岳麓书社</span></span></p><p><br/></p>",
        bookTags: [
            "wx"
        ]
    },
    resource: {
        learningPlan: "",
        mindGuide: ""
    },
    readItems: [
        "VideoStudy",
        "AudioStudy"
    ]
} );

 db.getCollection('book_course');

db.getCollection("book_course").insert( {
    _id: ObjectId("6010b973f69d7d1891215913"),
    bookId: "5ec624b405ce835be78f258e",
    cover: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170875964084.jpg",
    video: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170870092283.mp4",
    playTime: NumberInt("2728"),
    title: "第一课时 导读课:走进《茶馆》",
    briefIntro: "1.走进作者,了解作者创作的社会背景。 2.阅读舞台说明,获取相关的信息。 3.对比鉴赏,体会戏剧文化的博大精深。",
    grades: [
        NumberInt("10")
    ],
    studyStages: [
        NumberInt("3")
    ],
    link: "",
    mainLecturer: "黄金萍",
    lecturerIntro: "黄金萍,明德中学语文学科中心主任,长沙市蒋雁鸣语文名师工作室名师,长沙市卓越教师,湖南省中小学教师发展中心送培专家,2020年被评为湖南省特级教师。",
    fileSize: NumberInt("398440429"),
    orderNum: NumberInt("1")
} );
db.getCollection("book_course").insert( {
    _id: ObjectId("6010bab0ca27ab37be8d1a51"),
    bookId: "5ec624b405ce835be78f258e",
    cover: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170910232390.jpg",
    video: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170904600889.mp4",
    playTime: NumberInt("2621"),
    title: "第二课时 精读课:满纸寻常言,试解其中味 ——《茶馆》《龙须沟》的语言艺术",
    briefIntro: "1.阅读戏剧作品《茶馆》《龙须沟》,品味语言,建构言语经验,体会精彩语句的表现力,提高对戏剧文学语言的感受力。 2.感受作品中的思想和艺术魅力,发展想象力和创造力。 3.通过阅读和鉴赏戏剧作品,体会戏剧文化的博大精深、源远流长。",
    grades: [
        NumberInt("10")
    ],
    studyStages: [
        NumberInt("3")
    ],
    link: "",
    mainLecturer: "伍月娥",
    lecturerIntro: "伍月娥:长沙市明德中学教师,蒋雁鸣中学语文名师工作室优秀学员。获2019年湖南省中小学教师信息技术与学科深度融合在线集体备课大赛二等奖。\n",
    fileSize: NumberInt("383164066"),
    orderNum: NumberInt("2")
} );
db.getCollection("book_course").insert( {
    _id: ObjectId("6010bc90f69d7d1891215917"),
    bookId: "5ec624b405ce835be78f258e",
    cover: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170955107499.jpg",
    video: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170954999298.mp4",
    playTime: NumberInt("571"),
    title: "微课1:《茶馆》的结构艺术",
    briefIntro: "暂无",
    grades: [
        NumberInt("10")
    ],
    studyStages: [
        NumberInt("3")
    ],
    link: null,
    mainLecturer: "伍月娥",
    lecturerIntro: "伍月娥:长沙市明德中学教师,蒋雁鸣中学语文名师工作室优秀学员。获2019年湖南省中小学教师信息技术与学科深度融合在线集体备课大赛二等奖。",
    fileSize: NumberInt("11304239"),
    orderNum: NumberInt("3")
} );
db.getCollection("book_course").insert( {
    _id: ObjectId("6010bcb3ca27ab37be8d1a5a"),
    bookId: "5ec624b405ce835be78f258e",
    cover: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170959843322.jpg",
    video: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170959753421.mp4",
    playTime: NumberInt("505"),
    title: "微课2:《龙须沟》人物变化",
    briefIntro: "暂无",
    grades: [
        NumberInt("10")
    ],
    studyStages: [
        NumberInt("3")
    ],
    link: null,
    mainLecturer: "伍月娥",
    lecturerIntro: "伍月娥:长沙市明德中学教师,蒋雁鸣中学语文名师工作室优秀学员。获2019年湖南省中小学教师信息技术与学科深度融合在线集体备课大赛二等奖。",
    fileSize: NumberInt("9854681"),
    orderNum: NumberInt("4")
} );
db.getCollection("book_course").insert( {
    _id: ObjectId("6010bcd8f69d7d1891215918"),
    bookId: "5ec624b405ce835be78f258e",
    cover: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170964212401.jpg",
    video: "https://res.xh-er.com/yuedou/book/courseVideo/2021/0127/161170963687200.mp4",
    playTime: NumberInt("532"),
    title: "微课3:《龙须沟》戏剧冲突",
    briefIntro: "暂无",
    grades: [
        NumberInt("10")
    ],
    studyStages: [
        NumberInt("3")
    ],
    link: null,
    mainLecturer: "伍月娥",
    lecturerIntro: "伍月娥:长沙市明德中学教师,蒋雁鸣中学语文名师工作室优秀学员。获2019年湖南省中小学教师信息技术与学科深度融合在线集体备课大赛二等奖。",
    fileSize: NumberInt("39752851"),
    orderNum: NumberInt("5")
} );

2、需求:查询书本所对应的视频标题

3、执行的sql语句

db.getCollection('book').aggregate([
{$match: {"goods.goodsName": {
        $in: ["四维阅读一年级下册","四维阅读·读读童谣和儿歌(一)","四维阅读·读读童谣和儿歌(二)","四维阅读二年级下册","四维阅读·七色花","四维阅读·愿望的实现","四维阅读三年级下册","四维阅读·中国古代寓言","四维阅读·伊索寓言","四维阅读四年级下册","四维阅读·十万个为什么","四维阅读·灰尘的旅行","四维阅读五年级下册","四维阅读·西游记(青少年版)","四维阅读·三国演义(青少年版)","四维阅读六年级下册","四维阅读·鲁滨逊漂流记","四维阅读·爱丽丝漫游奇境","四维阅读七年级下册","四维阅读·海底两万里","四维阅读·骆驼祥子","四维阅读八年级下册","四维阅读·傅雷家书","四维阅读·钢铁是怎样炼成的","四维阅读九年级下册","四维阅读·儒林外史","四维阅读·简·爱","四维阅读高一年级下册","四维阅读·红楼梦","四维阅读·茶馆","四维阅读高二年级下册","四维阅读·谈美书简","四维阅读·朱自清散文","四维阅读·莫泊桑中短篇小说选","四维阅读·欧·亨利短篇小说选"]
    }}},
  { "$project": {
      "_id": {
        "$toString": "$_id"
      },
			"name":"$goods.goodsName"
    }},
  { "$lookup": {
    "from": "book_course",
    "localField": "_id",
    "foreignField": "bookId",
    "as": "comments"
  }},
	{
		"$unwind":"$comments"
	},{ "$project": {
			"bookName":"$name",
			"bookId":"$_id",
			"book_course_name":"$comments.title"
    }}
])
  1. 其中 .aggregate管道类似java中的stream(),先聚合
  2. {$match: {"goods.goodsName": {$in: ["四维阅读一年级下册","四维阅读·读读童谣和儿歌(一)"]}}}

    先在book中过滤;

  3. { "$project": { "_id": {"$toString": "$_id"},"name":"$goods.goodsName"}}

     在book表中_id 是objectId而book_course中booksId是字符串,在$lookup中不起作用所以需要转成一致的类型在这里就用$toString,并且获取书本名goodsName

  4. { "$lookup": {
        "from": "book_course",
        "localField": "_id",
        "foreignField": "bookId",
        "as": "comments"
      }}

    两张表联合的关键 ;

  5. {"$unwind":"$comments"}

     作用是将查询的数组剥离出来,如下;

  6.  继续用$project过滤出需要的字段;

    { "$project": {
    			"bookName":"$name",
    			"bookId":"$_id",
    			"book_course_name":"$comments.title"
        }}

     

     

4、效果 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MongoDB中,$lookup操作符可以用于实现连接查询。它可以将两个集合中的文档进行关联,并返回一个新的文档,其中包含了两个集合中匹配的文档信息。而在进行$lookup操作之后,我们可以使用$project操作符来对查询结果进行进一步的处理,以选择需要显示的字段或者添加新的字段。 例如,假设我们有两个集合"orders"和"customers",它们的结构分别如下: orders集合: ``` { "_id": ObjectId("5f94e5c0d286db2d3ad3a71c"), "order_id": 1, "customer_id": ObjectId("5f94e5c0d286db2d3ad3a71a"), "product": "computer", "amount": 3 } ``` customers集合: ``` { "_id": ObjectId("5f94e5c0d286db2d3ad3a71a"), "name": "Tom", "age": 25, "address": "New York" } ``` 现在我们希望查询orders集合中的文档,并将其与customers集合中的文档进行关联,以获订单对应的客户信息。我们可以使用以下的$lookup和$project操作来实现: ``` db.orders.aggregate([ { $lookup: { from: "customers", localField: "customer_id", foreignField: "_id", as: "customer_info" } }, { $project: { "order_id": 1, "product": 1, "amount": 1, "customer_name": "$customer_info.name", "customer_age": "$customer_info.age", "customer_address": "$customer_info.address" } } ]) ``` 在上述代码中,$lookup操作符用于将orders集合中的"customer_id"字段与customers集合中的"_id"字段进行关联,并将匹配的文档信息存储在一个新的字段"customer_info"中。而$project操作符则用于对查询结果进行处理,选择需要显示的字段,并添加新的字段"customer_name"、"customer_age"和"customer_address"来显示客户的姓名、年龄和地址。 参考资料: - MongoDB官方文档:$lookup - MongoDB官方文档:$project
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十方天士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值