Here is my data:
{
"_id": ObjectId("6213ba90a013b7c5f1232e1f"),
"name": "name1",
"surname": "surname1",
"newArray": {
"buyDate": ISODate("1975-11-04T13:14:15Z"),
"carCount": 3,
"name": "name1",
"surname": "surname1"
}
},
{
"_id": ObjectId("6213ba90a013b7c5f1232e2f"),
"name": "name2",
"surname": "surname2",
"newArray": {
"buyDate": ISODate("1978-12-07T15:30:15Z"),
"carCount": 7,
"name": "name2",
"surname": "surname2"
}
},
{
"_id": ObjectId("6213ba90a013b7c5f1232e3f"),
"name": "name3",
"surname": "surname3",
"newArray": {
"buyDate": ISODate("1983-11-12T18:40:15Z"),
"carCount": 4,
"name": "name3",
"surname": "surname3"
}
}
I want to calculate car counts by their buying month. First I want to find their buy month for all "newArray" and then add to all "newArray". I mean:
{
"_id": ObjectId("6213ba90a013b7c5f1232e1f"),
"name": "name1",
"surname": "surname1",
"newArray": {
"buyDate": ISODate("1975-11-04T13:14:15Z"),
"carCount": 3,
"name": "name1",
"surname": "surname1",
"buyMonth": 11
}
},
{
"_id": ObjectId("6213ba90a013b7c5f1232e2f"),
"name": "name2",
"surname": "surname2",
"newArray": {
"buyDate": ISODate("1978-12-07T15:30:15Z"),
"carCount": 7,
"name": "name2",
"surname": "surname2",
"buyMonth": 12
}
},
{
"_id": ObjectId("6213ba90a013b7c5f1232e3f"),
"name": "name3",
"surname": "surname3",
"newArray": {
"buyDate": ISODate("1983-11-12T18:40:15Z"),
"carCount": 4,
"name": "name3",
"surname": "surname3",
"buyMonth": 11
}
}
Lastly I will calculate car count by their buying month. I've tried but I do not get any result with this:
db.collection.aggregate([
{
$set: {
"newArray.buyMonth": "$buyDate.month"
}
},
{
"$group": {
"_id": "$buyMonth",
"carCountByMonth": {
"$count": "newArray"
}
}
}
])
How can I get what I want? Thanks in advance.
CodePudding user response:
- To get month from date, use
$month
operator. - To get
newArray.buyDate
, usenewArray.buyDate
but notbuyDate
. $group
bynewArray.buyMonth
but notbuyMonth
.- Use
$sum
to calculate sum of allnewArray.carCount
instead of$count
.
db.collection.aggregate([
{
$set: {
"newArray.buyMonth": {
$month: "$newArray.buyDate"
}
}
},
{
"$group": {
"_id": "$newArray.buyMonth",
"carCountByMonth": {
"$sum": "$newArray.carCount"
}
}
}
])