• mongo联集合查询


    一.联集合查询(mysql的跨表查询)

      要主要搞清楚那个是主集合,哪个是被查集合

    db.主集合.aggregate([
      {$lookup: {
        from: "被查集合",
        localField: "主集合字段名",
        foreignField: "被查集合字段名",
        as: "保存查询的结果字段名”
    }}
    
    ])

      先来看两个集合

      1.微博内容集合

          

       2.用户集合

      

     需求一

      通过微博集合,查询用户信息(微博内容对应的发布微博的用户信息)

    db.example_post.aggregate([
        {$lookup: {
               from: "example_user",
               localField: "user_id",
               foreignField: "id",
               as: "user_info"
             }}
        
        ]) 

             

       查询出来的user_info是一个列表,这个是因为被查询集合可能有多条数据与主集合的字段对应,用列表才能装下所有的数据

      我们使用$unwind  和¥project进一步美化输出结果

       1.先拆分user_info:

    db.example_post.aggregate([
        {$lookup: {
               from: "example_user",
               localField: "user_id",
               foreignField: "id",
               as: "user_info"
             }},
            {"$unwind": "$user_info"}
        ])

      

       现在user_info不再是一个列表,而是一个字典

      进一步提取name和work字段

      

    db.example_post.aggregate([
        {$lookup: {
               from: "example_user",
               localField: "user_id",
               foreignField: "id",
               as: "user_info"
             }},
            {"$unwind": "$user_info"},
            {$project: {
                content:1,
                post_time:1,
                "name":"$user_info.name",
                "work":"$user_info.work"
                
            }}
        ])

      

     需求二

      通过用户集合,查询微博信息(用户发布过的微博有哪些)

    db.example_user.aggregate([
        {"$lookup":{
            "from":"example_post",
            "localField":"id",
            "foreignField":"user_id",
            "as":"weibo_info"
        }}
        
        ])

      

       美化返回结果

    db.example_user.aggregate([
        {"$lookup":{
            "from":"example_post",
            "localField":"id",
            "foreignField":"user_id",
            "as":"weibo_info"
        }},
        {"$unwind":"$weibo_info"},
        {"$project"{
            "name":1,
            "work":1,
            "post_time":"$weibo_info.post_time",
            "content":"$weibo_info.content"
        }}
        ])

      

    摘自:《左手redis,右手mongodb》

  • 相关阅读:
    UICollectionView中使用 UICollectionViewFlowLayout进行布局(模仿苹果相册)
    使用CocoaPods被卡住:Updating local specs repositories
    【原】iOS 同时重写setter和getter时候报错:Use of undeclared identifier '_name';did you mean 'name'
    iOS 设置不同的字体颜色
    使用java代码,动态给TextView设置drawable
    格式化浮点数(保留指定位数)
    监听输入法的出现和隐藏
    dp和px的转换
    获取状态栏高度
    获取在attr.xml中声明的主题样式
  • 原文地址:https://www.cnblogs.com/tjp40922/p/13190501.html
Copyright © 2020-2023  润新知