问题
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.
回答1:
Since there are two collections, we need to use
$lookup
to join tow collections. Here I used uncorelated subqueries- The aggregation is performed in
colA
collections, but inside thelookup
'spipeline
we perform aggregation oncolB
.$unwind
helps to de-structure theitems
.$match
helps to eliminate unwanted data (match stage requires $expr). - Once our join is succeeded, we need to just count the array using
$size
$reduce
helps to sum the array value ofsize
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
来源:https://stackoverflow.com/questions/64734988/aggregation-with-multiple-criterias-and-sum-match-based-on-the-count-key