O
O
Oleg Ozimok2014-08-18 14:04:35
MongoDB
Oleg Ozimok, 2014-08-18 14:04:35

How to do double grouping in MongoDB?

Hello. For the first time I deal with MongoDB, a question arose when grouping data.
Given data for two days:

db.test.insert({
    "_id" : ObjectId("13edebb315d8952400407343"),
    "create_at" : ISODate("2012-12-19T12:00:00.000Z"),
    "item" : {
        "tags" : [ 
            "aaaa"
        ],
        "event" : "accepted",
    }
});
    
db.test.insert({
    "_id" : ObjectId("13edebb39e60c73800b35727"),
    "create_at" : ISODate("2012-12-19T12:05:00.000Z"),
    "item" : {
        "tags" : [ 
            "aaaa"
        ],
        "event" : "delivered"
    }
});

db.test.insert({
    "_id" : ObjectId("13edebb315d8952400407344"),
    "create_at" : ISODate("2012-12-19T13:40:00.000Z"),
    "item" : {
        "tags" : [ 
            "bbbb"
        ],
        "event" : "accepted",
    }
});

db.test.insert({
    "_id" : ObjectId("13edebb39e60c73800b35728"),
    "create_at" : ISODate("2012-12-19T13:45:00.000Z"),
    "item" : {
        "tags" : [ 
            "bbbb"
        ],
        "event" : "delivered"
    }
});

db.test.insert({
    "_id" : ObjectId("13edebb315d8952400407345"),
    "create_at" : ISODate("2012-12-20T16:30:00.000Z"),
    "item" : {
        "tags" : [],
        "event" : "accepted",
    }
});

db.test.insert({
    "_id" : ObjectId("13edebb39e60c73800b35729"),
    "create_at" : ISODate("2012-12-20T16:35:00.000Z"),
    "item" : {
        "tags" : [],
        "event" : "delivered"
    }
});

At the output, you need to get the result:
{
  "total_count": 6
  "items": [
    {
      "total_count": 2,
      "created_at": "Wed, 19 Dec 2012 00:00:00 GMT",
      "tags": {
        "aaaa": 1,
        "supporta": 1
      },
      "event": "sent"
    },
    {
      "total_count": 2,
      "created_at": "Wed, 19 Dec 2012 00:00:00 GMT",
      "tags": {
        "aaaa": 1,
        "supporta": 1
      },
      "event": "delivered"
    },
    {
      "total_count": 1,
      "created_at": "Wed, 20 Dec 2012 00:00:00 GMT",
      "tags": {},
      "event": "sent"
    },
    {
      "total_count": 1,
      "created_at": "Wed, 20 Dec 2012 00:00:00 GMT",
      "tags": {},
      "event": "delivered"
    }
}

So far, it has been possible to form part of the necessary data by requesting:
db.test.aggregate([ 
  {$group:      
   {          
     _id:{event:'$item.event', doy:{$dayOfYear:'$create_at'} },
     total_count:{$sum:1},
     created_at:{$first: '$create_at'},
     tags: {$addToSet: '$item.tags'}
   },
  },
  {$project:{total_count:1,  _id:0, event:'$_id.event', created_at:1, tags:1}}
])

But how to get the necessary information about the tags, that is, an array of tags and their number?
And also in the date indicate the beginning of the day 00:00:00?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question