mysql到mongodb查询转换问题

时间:2015-05-25 09:26:10

标签: mongodb-query

我是mongodb的新手。我尝试将这个mysql查询转换为mongodb,但我只获得(appId& count)。其实我想要(日期和数量)。

原始查询

SELECT count(distinct appID),created_date 
FROM table 
where created_date between 2015-1-1 and 2015-1-20 
group by created_date

mongodb查询

db.collection.aggregate(
    [{ $match : { createdDate: { $gt : ISODate("2015-05-01T00:00:00.000Z"), $lte : ISODate("2015-05-20T23:59:59.000Z")}}},
    {  $group : { _id : { year: { $year: "$createdDate" },month: { $month: "$createdDate" },day: { $dayOfMonth : "$createdDate" },appId : "$appId"}}},
    {  $group : { _id : { appIdd: '$_id.appId'}, count: { $sum: 1 }}},
    { $project: { _id : 0,appId: '$_id.appIdd', count: 1}}
    ])

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我认为您应该能够通过以下查询获得所需的结果:

db.collection.aggregate(
    [{ $match : { createdDate: { $gt : ISODate("2015-05-01T00:00:00.000Z"), $lte : ISODate("2015-05-20T23:59:59.000Z")}}},
    {  $group : { _id : { year: { $year: "$createdDate" },month: { $month: "$createdDate" },day: { $dayOfMonth : "$createdDate" },appId : "$appId"}}},
    {  $group : { _id : { appIdd: '$_id.appId'}, count: { $sum: 1 }}},
    { $project: { created_date_str: { $concat: ["$_id.year","-","$_id.month","-","$_id.day","T00:00:00Z"] }, count: 1}},
    { $project: { _id : 0, created_date: { ISODate("$created_date_str") }, count: 1}}
    ])