Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

nodejs 在mongodb在跨数据库之中如何进行关联起来查询,并且支持筛选关联表的条件进行查询

"班级数据库": "mongodb://192.168.3.17/xxx
"学生数据库": "mongodb://192.168.3.99/xxx (只读)

使用 mongoose.createConnection 进行链接2个数据库
classId 是唯一并且不会重复的。
学生数据库是只读的,并且数量非常大,并随时可能更新。

查询主要有2个问题:

  1. mongodb://xxx , 两个不相同ip数据库如何关联起来分页查询
  2. 传入cj查询班级只返回符合条件的班级列表、并且可能有其他同时筛选班级表的条件

班级表 mongodb://192.168.3.17/xxx

{ "_id" : 1, "name" : "高二(1)班", classId:"a1"}
{ "_id" : 2, "name" : "高二(2)班", classId:"a2"}
{ "_id" : 3, "name" : "高二(3)班", classId:"a3"}

学生表 mongodb://192.168.3.99/xxx

{ "_id" : x1, classId:"a1", "user" : "张三", "cj":['88','75']}
{ "_id" : x2, classId:"a2", "user" : "李四", "cj":['88','33','99']}

直接查询班级并关联学生表的列表为

count:2,
list: [
        {
            "_id" : 1, 
            "name" : "高二(1)班", 
            classId:"a1",
            xsxx:{
                "_id" : 'x1', 
                classId:"a1", 
                "user" : "张三", 
                "cj":['88','75']
            }
        },
         {
            "_id" : 2, 
            "name" : "高二(2)班", 
            classId:"a2",
            xsxx:{
               "_id" : 'x2', 
               classId:"a2", 
               "user" : "李四", 
               "cj":['88','33','99']
            }
        },
    ]

查询条件是 cj = ['33'] 时

count: 1,
list: [
         {
            "_id" : 2, 
            "name" : "高二(2)班", 
            classId:"a2",
            xsxx:{
               "_id" : 'x2', 
               classId:"a2", 
               "user" : "李四", 
               "cj":['88','33','99']
            }
        },
    ]

我通过网络搜索的答案如下,并没有帮助到我。

$lookup: { 
    from: "学生表",             // 关联到学生表
    localField: "classId",      // 班级表关联的字段
    foreignField: "classId",    // 学生表关联的字
    as: "学生信息"
}
      

我在graphql的做法是使用resolver调用查询

班级表.addRelation('学生对象信息', {
    resolver: () => 学生表.getResolver('findOne'),
    prepareArgs: {
        filter: (source) => {
            return { classId: source.classId }
        }
    },
    projection: { openid: true }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

什么数据库可以把两个不同的实例合在一起?据我所知反正mongo不得行吧,后面可以有多个地址,那个是副本集,还是属于一个数据库。副本集与分片那也是一个数据库实例啊。

既然数据都不在一个数据库,那就只能先查班级然后再去查找学生。
如果是一个数据库,这种关联的操作符是lookup,用聚合执行。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...