$project 为投射查询 ,即将一个数据结果映射为另一个结果 过程中可以对某些数据进行修改 控制其最终显示的结果。
1、原字段查询
原字段查询,_id-默认显示,0-表示不显示,1-表示显示,如何只是原字段查询和find()一致
db.test.aggregate(
{"$project":{
"_id":0,
"userid":1,
"price":1,
}})
效果: 
2、数学表达式查询
数学表达式查询,类型如下: {"$add":[expr1,expr2,...,exprN]} #相加 {"$subtract":[expr1,expr2]} #第一个减第二个 {"$multiply":[expr1,expr2,...,exprN]} #相乘 {"$divide":[expr1,expr2]} #第一个表达式除以第二个表达式的商作为结果 {"$mod":[expr1,expr2]} #第一个表达式除以第二个表达式得到的余数作为结果
注意:expr可以为字段也可以为具体数值,可以多个表达式一起使用。
效果: 
3、日期表达查询
日期表达查询:$year,$month,$week,$dayOfMonth,$dayOfWeek,$dayOfYear,$hour,$minute,$second ,可以多个组合,实际上就是对字段使用日期函数。
db.test.aggregate(
{
"$project":{
"userid":1,
"new_year":{
"$year":"$create_date"
},
"day":{
"$dayOfWeek":"$create_date"
},
"month":{
"$month":"$create_date"
}
}
})
效果:  比如:求时间差:
db.test.aggregate(
{"$project":{"name":1,"new_minute":{
"$subtract":[
{"$minute":new Date()},
{"$minute":"$create_date"}
]
}}}
)
效果: 
4、字符串表达式查询
常用类型如下: {"$substr":[自定义字符串|$字段名,起始位置,截取几个字节]} {"$concat":[expr1,expr2,...,exprN]} #指定的表达式或字符串连接在一起返回,只支持字符串拼接 {"$toLower":expr} {"$toUpper":expr}
截取字段:
db.test.aggregate( {"$project":{"str":{"$substr":["$price",0,1]}}})

截取自定义字符串:
db.test.aggregate( {"$project":{"str":{"$substr":["abcdef",1,2]}}})

拼接字段:
db.test.aggregate( {"$project":{"str":{"$concat":["$userid","1","2"]}}})

拼接字符串:
db.test.aggregate( {"$project":{"str":{"$concat":["abc","1","2"]}}})

|