zoukankan      html  css  js  c++  java
  • 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》

  • 相关阅读:
    拆分字符串为单条记录
    Howto: Change Windows Hostname and Keep Oracle 10g Running
    关于Oracle的MTS
    linux/centos Header V3 DSA signature: NOKEY, key ID 错误解决方法
    cacti0.8.7d安装
    Identifying Host Names and IP Addresses
    修改Oracle字符集(character set)
    企业管理器(OEM)介绍: Grid Control 和 Database Control
    搞OMS真折腾
    ORA12560: TNS: 协议适配器错误
  • 原文地址:https://www.cnblogs.com/tjp40922/p/13190501.html
Copyright © 2011-2022 走看看