MongoDB聚集多个查找条件
我有3个收藏。
db.a.insert([
{ "_id" : ObjectId("5b56989172ebcb11105e8f41"), "db_type":b, "number" : 1},
{ "_id" : ObjectId("5b56989172ebcb11105e8f42"), "db_type":c, "number" : 2},
])
db.b.insert([
{ "_id" : ObjectId("5b56989172ebcb11105e8f43"), "number" : 1, "value" : "111"},
])
db.c.insert([
{ "_id" : ObjectId("5b56989172ebcb11105e8f44"), "number" : 2, "value" : "222"},
])
我想根据db_type进行查找查询,以从每个集合中获取值。
在这种情况下,我该怎么办?
结果:
{ "_id" : ObjectId("5b56989172ebcb11105e8f41"), "db_type" : b, "number" : 1, "value" : "111"}
{ "_id" : ObjectId("5b56989172ebcb11105e8f42"), "db_type" : c, "number" : 2, "value" : "222"}
堵塞零件...
db.getCollection('a').aggregate([
{
"$lookup":{
"from": "b" or "c", // I want to give condition here.
"localField": "number",
"foreignField": "number",
"as": "result"
}
},
])
I have 3 collection.
db.a.insert([
{ "_id" : ObjectId("5b56989172ebcb11105e8f41"), "db_type":b, "number" : 1},
{ "_id" : ObjectId("5b56989172ebcb11105e8f42"), "db_type":c, "number" : 2},
])
db.b.insert([
{ "_id" : ObjectId("5b56989172ebcb11105e8f43"), "number" : 1, "value" : "111"},
])
db.c.insert([
{ "_id" : ObjectId("5b56989172ebcb11105e8f44"), "number" : 2, "value" : "222"},
])
I want to make a lookup query that gets values from each collection according to db_type.
What should I do in this case?
result :
{ "_id" : ObjectId("5b56989172ebcb11105e8f41"), "db_type" : b, "number" : 1, "value" : "111"}
{ "_id" : ObjectId("5b56989172ebcb11105e8f42"), "db_type" : c, "number" : 2, "value" : "222"}
clogged part...
db.getCollection('a').aggregate([
{
"$lookup":{
"from": "b" or "c", // I want to give condition here.
"localField": "number",
"foreignField": "number",
"as": "result"
}
},
])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您的情况,由于您只有2个情况
b
和c
可以从中查找。您可以简单地进行2个单独的查找,然后使用$ setunion
将结果分组在一起。这是 mongo playground 供您参考。
For your case, as you have only 2 cases
b
andc
to lookup from. You can simply do 2 separate lookups and use$setUnion
to group the results together.Here is the Mongo playground for your reference.