查询一个字段有哪几种取值

# MySQL
SELECT DISTINCT(fieldname) FROM tblname;
// MQL
db.tblname.distinct("fieldname");

取字段的前 2 位并去重

# MySQL
SELECT DISTINCT(SUBSTR(fieldname, 1, 2)) FROM tblname; 
// MQL
db.collname.aggregate(
    [
        {
            $project: { tmp: { $substr: ["$fieldname", 0, 2] } }
        },
        {
            $group: { _id: null, result: { $addToSet: "$tmp" } }
        }
    ]
);

统计一个字段的几种取值,并按统计量降序排列。

# MySQL
SELECT fieldname, COUNT(*)
FROM tblname
GROUP BY fieldname
ORDER BY COUNT(*) DESC;
// MQL
db.task.aggregate(
    [
        {
            $group: {
                _id: "$fieldname",
                count: { $sum: 1 }
            }
        },
        {
            $sort: { count: -1 }
        }
);
本文出自 qbit snap

qbit
268 声望279 粉丝