1

Aggregation in MongoDB

Collections blocks

{
    "_id": ObjectId("512eef329d5d0c9415000025"),
        "tx": {
         "0": "A1",
         "1": "A2",
         "2": "A3"
        },
    "time": NumberInt(1304200205)
} 

{
    "_id": ObjectId("512eef329d5d0c9415000026"),
        "tx": {
         "0": "A4",
         "1": "A5",
         "2": "A6"
        },
    "time": NumberInt(1304200395)
} 

{
    "_id": ObjectId("512eef329d5d0c9415000027"),
        "tx": {
         "0": "A7",
         "1": "A8",
         "2": "A9"
        },
    "time": NumberInt(1304202305)
} 

db.blocks.aggregate(
    {'$unwind':'$tx'},
    {'$group' : { '_id' : {
        'year': {'$year':'$time'},
        'month': {'$year':'$time'},
        },
        'count' : {'$sum':1}            
    }
});

{
    "errmsg" : "exception: can't convert from BSON type NumberInt32 to Date",
    "code" : 16006,
    "ok" : 0
}

Which means that the time field is not in Mongo Date format but as NumberInt32.

How do I convert it to MongoDate using aggregate function. I do not want to change the data, because it is coming from a different source, which I import every hour. There are about 2,000,000 records in the DB at present and is increasing...

The question was raised Aggregation Framework - Converting Unix Timestamp to ISODate about 1 month back. If some one has an answer please post it here too...

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Nilam Doctor
  • 491
  • 7
  • 18

0 Answers0