0

So I'm trying to make an aggregation query. I have documents that look like this:

{
    "_id": ObjectId(),
    "value": [1,2],
    "date": ISODate("2016-06-02T03:02:00.000Z")
},
{
    "_id": ObjectId(),
    "value": [1,2],
    "date": ISODate("2016-06-06T03:02:00.000Z")
},
{
    "_id": ObjectId(),
    "value": [3,2],
    "date": ISODate("2017-04-06T03:02:00.000Z")
}

I want to count the number of times the same array, value has occurred in a specific year-month.

I have gotten the date by writing this aggregation:

{
    "$group":
    {
        '_id':
        {
            "$dateToString":
            {
                "format": "%Y-%m",
                "date": "$launch_time"
            }
        }
    }
},
{
    "$sort":
    {
        "_id": -1
    }
},
{
    "$project":
    {
        "date": "$_id",
        "_id": 0,
    }
}

Which gives me the result:

{'date': '2016-04'} ..so on

And I've managed to count the arrays with:

{
    "$group":
    {
        "_id": "$home_coordinates",
        "count":
        {
            "$sum": 1
        }
    }
}

Which gives me the output:

{'_id': [1,2], 'count': 2} ..so on

How do I combine these 2 in such a way that my result looks like this?

{
    "date": "2016-06",
    "value": [1,2],
    "count": 2
},
{
    "date": "2017-04",
    "value": [3,2],
    "count": 1
}

Hence, how do I count the similar arrays based on date?

hrishikeshpaul
  • 459
  • 1
  • 11
  • 27

1 Answers1

0

Try with this

db.collection.aggregate([
{
$addFields:{
    date:{ $substr: ["$date", 0, 10] }

    }
},
{
$group:{
    _id:"$date",
    date:{$first:"$date"},
    value:{$first:"$value"},
    count:{$sum:1}
    }
}
])
Ashwanth Madhav
  • 1,084
  • 1
  • 9
  • 21