mongo加入两个集合
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongo加入两个集合相关的知识,希望对你有一定的参考价值。
我有两个mongo集合:
- 埋
"_id" : ObjectId("8570bebcb7db3"), "fields" : [ { "control" : { "appearance" : "field-list" }, "children" : [ { "bind" : { "required" : "yes" }, ...
- 数据
"_id" : ObjectId("1570bf18a7db"), "defn" : ObjectId("8570bebcb7db3"), "data" : { "country" : "", "age" : 1, "age_unit" : "years", }, "label" : "type"
在defn._id = data.defn的地方加入
如何编写查询以返回defn._id的data.label?查询的格式为db.defn.find({data.label其中defn._id =“X”})
答案
如果您使用的是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"
// } ]
// }
另一答案
您可能想要尝试此模块@coolgk/mongo,它允许您加入并过滤多个集合。
例子
SQL to Mongo Join
Left JoinSELECT * 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'
}
}, { ... }, ... ]
Inner Join with Constraints
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'
}
}]
Inner Join on Mulitple Collections
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'
}
}
}]
以上是关于mongo加入两个集合的主要内容,如果未能解决你的问题,请参考以下文章
mongo-> 如何从两个不同的集合中获取日期时间 desc 顺序的记录