mongo加入两个集合

时间:2016-08-03 18:21:11

标签: mongodb mongoid mongodb-query pymongo

我有两个mongo集合:

  1. DEFN

    "_id" : ObjectId("8570bebcb7db3"), 
    "fields" : [    {      
    "control" : {   "appearance" : "field-list" },  
    "children" : [ {       "bind" : {      "required" : "yes" },   ...
    
  2. 数据

    "_id" : ObjectId("1570bf18a7db"),
    "defn" : ObjectId("8570bebcb7db3"),
    "data" : {
            "country" : "",
            "age" : 1,
            "age_unit" : "years", 
    },
    "label" : "type"
    
  3. 加入defn._id = data.defn

    的地方

    如何编写查询以返回defn._id的data.label? 查询将是表单 db.defn.find({data.label where defn._id =“X”})

2 个答案:

答案 0 :(得分:2)

如果您正在使用MongoDB 3.2,$lookup阶段可以执行左外连接的等效操作。

文档提供了使用此操作的示例here

使用您的数据的示例:

db.defn.insert({
  "_id" : "123456", 
  "some_text" : "main document"
})

db.data.insert( { 
  "defn" : "123456",
  "label" : "data we want to access"
})

db.defn.aggregate( [ 
  { "$lookup" : {
     "from" : "data",
     "localField" : "_id", 
     "foreignField" : "defn",
     "as" : "defns"
    }
  } 
])

// Results:
// { 
//   "_id" : "123456", 
//   "some_text" : "main document", 
//   "defns" : [ { 
//      "_id" : ObjectId("57a2cbbbeb99ff285a1f0893"), 
//      "defn" : "123456", 
//      "label" : "data we want to access" 
//    } ] 
// }

答案 1 :(得分:0)

您可能想尝试使用此模块@coolgk/mongo,它允许您加入并过滤多个集合。

实施例

SQL to Mongo Join

左加入

SELECT * FROM a LEFT JOIN b ON a.b_id = b.id

变为

model.find({}, {
    join: [ { on: 'b_id' } ]
})

结果:

[{
    _id: '5a8bde4ae2ead929f89f3c42',
    a_name: 'aname1',
    b_id: {
        _id: '5a8bde4ae2ead929f89f3c41',
        b_name: 'bname1'
    }
}, { ... }, ... ]
内约加入约束

SELECT * FROM a, b WHERE a.b_id = b.id AND b.b_name = 'bname1'

变为

model.find({}, {
    join: [ { on: 'b_id', filters: { b_name: 'bname1' } } ]
})

结果:

[{
    _id: '5a8bdfb05d44ea2a08fa8a4c',
    a_name: 'aname2',
    b_id: {
        _id: '5a8bdfb05d44ea2a08fa8a4b',
        b_name: 'bname2'
    }
}]
内部加入Mulitple馆藏

SELECT * FROM a, b, c WHERE a.b_id = b.id AND b.c_id = c.id AND c.c_name = 'cname3'

modela.find({}, {
    join: [{
        on: 'b_id',
        join: [{
            on: 'c_id',
            filters: { c_name: 'cname3' }
        }]
    }]
})

结果:

[{
    _id: '5a8bdfc1b07af22a12cb1f0b',
    a_name: 'aname3',
    b_id: {
        _id: '5a8bdfc1b07af22a12cb1f0a',
        b_name: 'bname3',
        c_id: {
            _id: '5a8bdfc1b07af22a12cb1f09',
            c_name: 'cname3'
        }
    }
}]