Skip to main content
3 of 5
edited body
RameshKumar
  • 163
  • 1
  • 17

Aggregate when local field is a key in array of object from another collection

I was trying get to get the count of element that is present in the array of objects in another collection.

Example:

#CollectionA

{ _id:1, name:"Sample1" }

{ _id:2, name:"Sample 2" }

{ _id:3, "name":"Sample 3" }

{ _id:4, "name":"Sample 4" }

#Collection B

{ _id:11, items:[ {_id:1, name:"sample1"},{_id:3, name:"sample 3"}] }

{ _id:12, items:[ {_id:1, name:"sample1"},{_id:3, name:"sample 3"}] }

{ _id:13, items:[ {_id:2, name:"sample2"},{_id:1, name:"sample 1"}], is_delete:true }

{ _id:14, items:[ {_id:1, name:"sample1"},{_id:3, name:"sample 3"}] }

Note: The _id in items is string.

#Expected Output

{ _id:1, name:"Sample1", count:3 }

{ _id:2, name:"Sample 2", count:0 }

{ _id:3, "name":"Sample 3", "count":3 }

{ _id:4, "name":"Sample 4", "count":0 }

Please help me to write a mongo query to get the expected out put.

RameshKumar
  • 163
  • 1
  • 17