0

I have the collection "A" like this

{
"_id" : ObjectId("5c4c1f2a5173562961468b30"),
"name" : "first"
},
{
"_id" : ObjectId("57c162f267045ec439ba2485"),
"name" : "second"
}

Like above i have multiple doc in a collection,

Now i have colection "B" like below which has _id of Collections a's doc

{
"_id" : ObjectId("57d14ad36495a197593ab7ab"),
"a_id" : ObjectId("5c4c1f2a5173562961468b30"),
"name" : "ab"
},
{
"_id" : ObjectId("57d941503dd051cc04205e1e"),
"a_id" : ObjectId("5c4c1f2a5173562961468b30"),
"name" : "cd "
}

Now i need a query that will give me result collection "A" based on how many documents are associated with "B"

If "A" has 2 documents in "B" I need those 2 "B" documents

Alejandro Vales
  • 2,816
  • 22
  • 41
Foram Sojitra
  • 391
  • 9
  • 19

1 Answers1

0

This simple aggregation make your result

 db.A.aggregate([
  {
    "$lookup": {
      "from": "B",
      "localField": "_id",
      "foreignField": "a_id",
      "as": "docuentInB"
    }
  },
  {
    $match: {
      $expr: { $gte: [{ $size: "$docuentInB" }, 2 ] }
    }
  },
  {
    $project: {
      docuentInB: 0
    }
  }
])
Ashok
  • 2,846
  • 1
  • 12
  • 20