查询MongoDb聚合联接两个集合
我需要查询mongoDb的帮助 所以我有两个收藏,比如 A组:查询MongoDb聚合联接两个集合,mongodb,mongodb-query,Mongodb,Mongodb Query,我需要查询mongoDb的帮助 所以我有两个收藏,比如 A组: {someField: "123", anotherField: "456"}, {someField: "1234", anotherField: "4567"} B组 {someField: "123", otherField: "789"} 带查询: db.A.aggregate([ { $lookup: { from: "B", let: {
{someField: "123", anotherField: "456"},
{someField: "1234", anotherField: "4567"}
B组
{someField: "123", otherField: "789"}
带查询:
db.A.aggregate([
{
$lookup:
{
from: "B",
let: { someField: "$someField", otherField: "$otherField" },
pipeline: [
{ $match:
{ $expr:
{ $and:
[
{ $eq: [ "$someField", "$$someField" ] },
{ $eq: [ "$otherField", "789" ] }
]
}
}
},
],
as: "B"
}
}
])
我得到所有集合A,其中B在{someField:“1234”,另一个字段:“4567”}
我想要实现的是:
{someField: "123", anotherField: "456", b: {someField: "123", otherField: "789"}}
提前谢谢您只需在let部分声明
$someField
db.collectionA.aggregate([
{
$lookup:{
摘自:'collectionB',
let:{some_字段:'$someField'},
管道:[
{$match:{
$expr:{
美元及:[
{$eq:[“$someField”,“$$some_field”]},
{$eq:[“$otherField”,“789”]}
]
}
}
}
],
如:‘B’
}
},
{
$match:{
$expr:{
$gt:[{$size:$B},0]
}
}
}
])
我就是这样删除空的
B
数组文档的:
db.A.aggregate( [
{
$lookup: {
from: "B",
localField: "someField",
foreignField: "someField",
as: "B"
}
},
{
$addFields: {
B: {
$filter: {
input: "$B",
cond: {
$eq: [ "$$this.otherField", "789" ]
}
}
}
}
},
{
$match: {
$expr: {
$gt: [ { $size: "$B" }, 0 ]
}
}
}
] ).pretty()
如果
B
数组大小大于零,则可以在查找后过滤文档(请参阅)。@prasad\uu如何做到这一点?请注意,请查看更新的代码。它仍然显示所有集合A,而不仅仅是包含集合B的集合A…@dImasAnggaSaputra您可以反转查找或添加$match阶段。更新了我上面的答案。