Reputation: 1228
I have a date as below in mongoDB.
[
{
condition: {
test: [
{ ...},
{ ...},
{ ...}
]
}
},
{
condition: {
test: [
{ ...},
{ ...}
]
}
},
...
]
And I want to get a sum value of test. For example, ('the number of test' - 1) and sum them.
In this case, (3 - 1) + (2 - 1) = 3. How can I make this sum value at one time using one aggregate of Mongodb?
Thank you so much for reading it.
Upvotes: 0
Views: 66
Reputation: 416
db.collectionName.aggregate([
{
$group:
{ _id: null,
totalSize:
{ $sum:
{ $add:
[{ $size: "$test"},-1]
}
}
}
}
])
Tested over the below data
/* 1 */
{
"_id" : ObjectId("5e31333fab4013230264d786"),
"condition" : "testCase1",
"test" : [
ISODate("2020-01-29T07:26:42.491Z"),
ISODate("2020-01-29T07:27:42.491Z")
]
}
/* 2 */
{
"_id" : ObjectId("5e313346ab4013230264d787"),
"condition" : "testCase2",
"test" : [
ISODate("2020-01-29T07:25:42.491Z"),
ISODate("2020-01-29T07:24:42.491Z"),
ISODate("2020-01-29T07:23:42.491Z")
]
}
Output :
{
"_id" : null,
"totalSize" : 3.0
}
Upvotes: 1