search

Home  >  Q&A  >  body text

mongoose - mongodb连表查询

mongo如何连表查询,比如有一个users 还有一个blogs 输出 blogs内容和作者信息

淡淡烟草味淡淡烟草味2762 days ago808

reply all(4)I'll reply

  • 黄舟

    黄舟2017-04-27 09:04:18

    mongodb不支持关系数据库的join(Connection) Query

    reply
    0
  • 習慣沉默

    習慣沉默2017-04-27 09:04:18

    eg:

    db.users.insert({name:'tmac',blogid:1});
    db.blog.insert({id:1,detail:'tmacs blog'});
    

    users has an attribute blogid and the id of blogs are one-to-one:

    db.users.find().forEach(function(x){
    var blogs_record = db.blogs.findOne({id:x.blogid});
    if(blogs_record != null){
    db.temp.insert({name:x.name,detail:blogs_record.detail});
    }
    )
    

    eg:

    db.users.insert({name:'tmac',blogid:1});
    db.blog.insert({id:1,detail:'tmacs blog1'});
    db.blog.insert({id:1,detail:'tmacs blog2'});
    

    users has an attribute blogid and the id of blogs is a pair of n:

    db.users.find().forEach(function(x){
    db.blogs.findOne({id:x.blogid}).forEach(function(y){
    db.temp.insert({name:x.name,y.detail});
    })
    )

    reply
    0
  • 漂亮男人

    漂亮男人2017-04-27 09:04:18

    Blogs can directly embed the author's information as a sub-document of blogs.

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-04-27 09:04:18

    mongoose provides the populate method to implement join. But I don’t understand it either~
    http://www.nodeclass.com/api/mongoose.html#guide_populate

    A relatively simple but clumsy method is to check one table first, then forEach the result and then query another table like the answer above.

    reply
    0
  • Cancelreply