u 为用户名,p为密码
本人使用的Mongodb可视化工具为robomongo(https://robomongo.org/)
上面的代码为数据格式 创建索引
db.getCollection('user').ensureIndex({"gender":1})//单个索引 db.getCollection('user').ensureIndex({"gender":1,"disabled":1})//复合索引其中user为表名,gender为想要创建索引的字段,1代表正序,-1代表倒序 如想要查询性别的男的数据
db.getCollection('user').find({"gender":"male"})性别为男的count
db.getCollection('user').count({"gender":"male"})性别为男且手机号为13101044567的数据
db.getCollection('user').count({"gender":"male","mobile":13101044567})范围查询
db.getCollection('user').find({"create_timestamp":{$gt:1499689304,$lt:1499689307}})gt大于 gte 大于等于 lt小于 lte 小于等于 模糊查询 db.getCollection(‘user’).find({“address”:/回/}) 注:需要注意的是mongodb的查询是区分int类型和string类型的,存储数据和查询的时候需要注意下。
语法:db.collection.aggregate(pipeline, options)
【pipeline $group参数】 $group : 将集合中的文档分组,可用于统计结果,$group首先将数据根据key进行分组。 $group语法: { $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } } _id 是要进行分组的key $group:可以分组的数据执行如下的表达式计算: $sum:计算总和。 $avg:计算平均值。 $min:根据分组,获取集合中所有文档对应值得最小值。 $max:根据分组,获取集合中所有文档对应值得最大值。 $push:将指定的表达式的值添加到一个数组中。 $addToSet:将表达式的值添加到一个集合中(无重复值)。 $first:返回每组第一个文档,如果有排序,按照排序,如果没有按照默认的存储的顺序的第一个文档。 $last:返回每组最后一个文档,如果有排序,按照排序,如果没有按照默认的存储的顺序的最后个文档。简单的例子
db.user.aggregate([{$group:{_id:"$gender",count:{$sum:1}}}]) db.user.aggregate([{$match:{"relations.office_id":168}},{$group:{_id:"$gender",count:{$sum:1}}}])注:match 要写到group的前面,否则查询不出数据
除聚合外,大部分查询和Mysql一样。 aggregate分组查询
$q = new \yii\mongodb\Query(); $pipelines[] = ['$match'=>['city_id'=>"$areaId"]]; $pipelines[] = ['$match'=>['report_date'=>$dateData]]; $pipelines[] = ['$match'=>['type'=>$userType]]; $pipelines[] = ['$sort'=>['report_date'=>1]];//1正序 -1倒序 $dataList = $q->from('tbl_user_report')->getCollection()->aggregate($pipelines); $q = new \yii\mongodb\Query(); $pipelines[] = [ '$group' => [ '_id' => '$FMobileTerminal', 'count' => [ '$sum' => 1 ] ], ]; $res = $q->from('user_center')->getCollection()->aggregate($pipelines);