我有这样的集合“ A”
{
"_id" : ObjectId("5c4c1f2a5173562961468b30"),
"name" : "first"
},
{
"_id" : ObjectId("57c162f267045ec439ba2485"),
"name" : "second"
}
像上面一样,我在一个集合中有多个文档,
现在,我有如下所示的集合“ B”,其中包含集合ID _id的文档
{
"_id" : ObjectId("57d14ad36495a197593ab7ab"),
"a_id" : ObjectId("5c4c1f2a5173562961468b30"),
"name" : "ab"
},
{
"_id" : ObjectId("57d941503dd051cc04205e1e"),
"a_id" : ObjectId("5c4c1f2a5173562961468b30"),
"name" : "cd "
}
现在我需要一个查询,该查询将基于与“ B”关联的文档数量为我提供结果集合“ A”
如果“ A”在“ B”中有2个文档,我需要那2个“ B”文档
答案 0 :(得分:0)
这种简单的聚合使您获得结果
db.A.aggregate([
{
"$lookup": {
"from": "B",
"localField": "_id",
"foreignField": "a_id",
"as": "docuentInB"
}
},
{
$match: {
$expr: { $gte: [{ $size: "$docuentInB" }, 2 ] }
}
},
{
$project: {
docuentInB: 0
}
}
])