【问题标题】:Aggregate multiple documents and count sum fieldAggregate multiple documents and count sum field
【发布时间】:2022-12-19 09:39:43
【问题描述】:
Document:
{
_id: "___"
finish: false or true
... some field..
}
Aggregate result:
{
finish: 10,
non_finish: 3,
results: [
docuemnt,
docuemnt,
...
]
}
Is it possible? I know how can I count finish, with condition
but how to aggregate document array?
【问题讨论】:
标签:
mongodb
aggregation-framework
【解决方案1】:
Solution 1
-
$set - Set finish_count and non_finish_count fields by checking the finish, if match then 1, else 0.
-
$group - Group by null, sum the finish_count and non_finish_count fields. Add each document into documents array.
-
$unset - Remove documents.finish_count and documents.non_finish_countfields.
db.collection.aggregate([
{
$set: {
finish_count: {
$cond: {
if: {
$eq: [
"$finish",
true
]
},
then: 1,
else: 0
}
},
non_finish_count: {
$cond: {
if: {
$eq: [
"$finish",
false
]
},
then: 1,
else: 0
}
}
}
},
{
$group: {
_id: null,
finish: {
$sum: "$finish_count"
},
non_finish: {
$sum: "$non_finish_count"
},
documents: {
$push: "$$ROOT"
}
}
},
{
$unset: [
"documents.finish_count",
"documents.non_finish_count"
]
}
])
Sample Mongo Playground (Solution 1)
Solution 2
-
$group - Group by null, and add each document into the documents array.
-
$set - Set the fields by counting the size ($size) of the array by filtering the document with finish (finish: true) and non_finish (finish: false) from the documents array.
db.collection.aggregate([
{
$group: {
_id: null,
documents: {
$push: "$$ROOT"
}
}
},
{
$set: {
finish: {
$size: {
$filter: {
input: "$documents",
cond: {
$eq: [
"$$this.finish",
true
]
}
}
}
},
non_finish: {
$size: {
$filter: {
input: "$documents",
cond: {
$eq: [
"$$this.finish",
false
]
}
}
}
}
}
}
])
Sample Mongo Playground (Solution 2)