V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐工具
RoboMongo
推荐书目
50 Tips and Tricks for MongoDB Developers
Related Blogs
Snail in a Turtleneck
leven87
V2EX  ›  MongoDB

MongoDB 如何在对象中进行联合查询?

  •  
  •   leven87 · 2019-07-23 15:24:11 +08:00 · 10393 次点击
    这是一个创建于 1710 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我使用 apollo server 通过 mongoose 连接 mongodb 进行后台开发。 现在遇到了一个问题,一个 collection Components 的结构为:

    Components {
    	coreInformation {
        	reflowId: String
            type: String
            ...    
        }
    	flowInformation {
        	owner: String
            user: String
            ...
        }
    
    }
    

    另一个 collection Vessels 的结构为:

    Vessels	{
    	imo: String
    	name: String
    }
    
    

    在 Components.flowInformation.user 中存储的是 Vessels.imo, 现在前端是列表显示 components,需要得到 Vessels.name,在传统的数据库中,有联合查询,很容易搞定。 但是在 mongoDB 中没有,我看网上说可以用 Populate+ Ref 搞定,但是我的 user 是包在 flowInformation 这个对象中的,我没有看到相关的例子。请 V 友帮忙,该如何使用,或者有其它的办法。谢谢。

    PS:并不想把 name 作为冗余数据也放到 component 中,因为会改变原有 document 结构,改动太大。

    第 1 条附言  ·  2019-07-23 18:51:26 +08:00

    看来这个帖子要自己结贴了, 使用 mongoose 中的 virtual populate 功能可以实现联合查询,方法就是在schma里面要配置一下外键,具体可以参考 https://mongoosejs.com/docs/populate.html#populate-virtuals, 记得要加上 { toJSON: { virtuals: true }, toObject: { virtuals: true }}, 否则同样出不来。

    我的schema代码:

    componentSchema.virtual("vessel", {
      ref: "MongoVessel", // The model to use
      localField: "flowInformation.user", // Find people where `localField`
      foreignField: "imo", // is equal to `foreignField`
      // If `justOne` is true, 'members' will be a single doc as opposed to
      // an array. `justOne` is false by default.
      justOne: false
    });
    
    
    6 条回复    2019-07-24 08:35:51 +08:00
    pifuant
        1
    pifuant  
       2019-07-23 18:31:19 +08:00
    mongo 不支持 join, 认命吧
    jk1030
        2
    jk1030  
       2019-07-23 18:38:58 +08:00
    nosql
    lqzhgood
        3
    lqzhgood  
       2019-07-23 18:50:16 +08:00 via Android   ❤️ 1
    前几天刚碰到这个问题
    mongoose 的虚拟属性支持这个



    https://mongoosejs.com/docs/populate.html
    # Populate Virtuals
    leven87
        4
    leven87  
    OP
       2019-07-23 18:52:10 +08:00
    @lqzhgood 哈哈,感谢,想到一块了
    bankroft
        5
    bankroft  
       2019-07-23 18:52:41 +08:00 via Android
    $lookup ?
    ilucio
        6
    ilucio  
       2019-07-24 08:35:51 +08:00 via Android
    mongodb 4.0 后可以用 lookup 实现联合查询了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1450 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 17:25 · PVG 01:25 · LAX 10:25 · JFK 13:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.