mongo 查询汇总
字符串拼接:
code: {$concat: ["$str1", " ", "$str2"]}
字符串拼接(某一字段没有或者为空时,会导致拼接串为空,所以需要判空):
code: {$concat: [
{$ifNull: [ "$str1", "" ]},
" ",
{$ifNull: [ "$str2", "" ]}
]}
判空(如果第一个表达式为空,则赋值为第二个表达式值;否则赋值第一个表达式值):
{$ifNull: [ "$str1", "" ]}
日期格式化为字符串:
createTime: {
$dateToString: {
format: "%Y-%m-%d %H:%M:%S",
date: "$createTime"
}
}
日期转为时间戳:
createTime: {
$toString:{$toLong:"$createTime"}
}
条件语句
sex: {
$cond: {
if: { $eq: [ "$sex", "boy"] },
then: "男",
else: "女"
}
}
// else 里可以再放 $cond,实现 if-else if-else。例如:
else: {
$cond: {
...
}
}
分组 group (group 单字段/多字段)
$sum、$avg、$min、$max
$push
:在结果文档中插入值到一个数组中$addToSet:在结果文档中插入值到一个数组中,但不创建副本
$first
:获取第一个文档数据
$last
:获取最后一个文档数据
{
$group: {
// group 单字段 (按课程分组,累加成绩)
// _id: "$course",
// group 多字段 (按班级、课程分组,累加成绩)
_id: {"classs": "$classs", "course": "$course"},
score: {$sum: "$score"}
}
}
字符串截取
substr{$substr: [ "$updateTime", 0, 10]}
map_reduce
按年龄统计数量:
db.collection.mapReduce(
function() { emit(this.age,1); },
function(key, values) {return Array.sum(values)},
{
query:{age: {"$exists": true}},
out:"collecction_out"
}
).find()
按年龄分组:
db.collection.mapReduce(
function() { emit(this.age, this.name); }, // map映射函数
function(key, values) { // reduce统计函数
return {datas: values};
},
{
query:{age: {"$exists": true}}, // 查询collection集合中年龄存在的记录
out:"collecction_out" // 将mapReduce结果输出到collection_out集合
}
).find()