mongodb的一些常用查询方法总结

  1. sql: select distinct(`item`) from `table` where `condition_start` > start and `condition_end` < end;
    mongo: db.table.distinct(“item”, {“condition_start” : {“$gt” : start}, “condition_end” : {“$lt” : end}});
  2. sql: select count(distinct(`item`)) from `table` where `condition_start` > start and `condition_end` < end;
    mongo: db.table.aggregate([{“$group”: {“_id”:”$item”, “count” : {“$sum” : 1}}}, {“$group”:{“_id”:1,”totalCount”:{“$sum”: “$count”}, “distinctCount”:{“$sum”:1}}}])
  3. sql: select count(distinct(`item`)) from `table` where `condition_start` > start and `condition_end` < end group by `another`
    mongo: db.table.aggregate([{“$group” : {“_id” : {“item_id” : “$item”, “another_id” : “$another”}, “count” : {“$sum” : 1}}}, {“$group” : {“_id” : “$_id.another_id”, “distinctCount” : {“$sum” : 1}, “total” : {“$sum” : “$count”}}}])

参考资料

  SQL to Aggregation Mapping Chart