Reputation: 163
I was trying get to get the count of element that is present in the array of objects in another collection. Example:
Collection A:
{
_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",size:1},{_id:3, name:"sample 3",size:5}]
}
{
_id:12,
items:[ {_id:1, name:"sample1",size:2},{_id:3, name:"sample 3",size:6}]
}
{
_id:13,
items:[ {_id:2, name:"sample2", size:5},{_id:1, name:"sample 1",size:8}],
is_delete:true
}
{
_id:14,
items:[ {_id:1, name:"sample1",size:3},{_id:3, name:"sample 3",size:1}]
}
Note: The _id in items is string.
Expected Output:
{
_id:1,
name:"Sample1",
count:6
}
{
_id:2,
name:"Sample 2",
count:0
}
{
_id:3,
"name":"Sample 3",
"count":12
}
{
_id:4,
"name":"Sample 4",
"count":0
}
Please help me to write a mongo query to get the expected out put.
Upvotes: 2
Views: 316
Reputation: 8894
Since there are two collections, we need to use
$lookup
to join tow collections. Here I used uncorelated subqueriescolA
collections, but inside the lookup
's pipeline
we perform aggregation on colB
. $unwind
helps to de-structure the items
. $match
helps to eliminate unwanted data (match stage requires $expr).$size
$reduce
helps to sum the array value of size
The mongo script is given below.
db.colA.aggregate([
{
$lookup: {
from: "colB",
let: {
bid: "$_id"
},
pipeline: [
{
$match: {
$or: [
{
is_delete: false
},
{
is_delete: {
"$exists": false
}
}
]
}
},
{
$unwind: "$items"
},
{
$match: {
$expr: {
$eq: [
"$items._id",
"$$bid"
]
}
}
},
],
as: "data"
}
},
{
$project: {
count: {
$reduce: {
input: "$data",
initialValue: 0,
in: {
$add: [
"$$value",
"$$this.items.size"
]
}
}
}
}
}
])
Working Mongo playground
Upvotes: 1