yii2简单使用mongodb(创建索引,简单查询,聚合查询)

xiaoxiao2021-02-28  113

yii2简单使用mongodb(创建索引,简单查询,聚合查询)

配置及工具

'mongodb' => [ 'class' => 'wii\mongodb\Connection', "dsn" => "mongodb://u:p@127.0.0.1:27017/admin" ],

u 为用户名,p为密码

本人使用的Mongodb可视化工具为robomongo(https://robomongo.org/)

创建索引,简单查询

{ "disabled" : "1", "gender" : "male", "identity_cards" : "12312341231234123", "mobile" : "13101044567", "address" : "回龙观", "birth_year" : 1938, "relations" : [ { "office_id" : 168, "city_id" : 10000011, "user_type" : "normal", "desc" : "one" }, { "office_id" : 235, "app_id" : 10000013, "user_type" : "name", "desc" : "two" }, { "office_id" : 168, "app_id" : 10000006, "user_type" : "normal", "desc" : "three" } ], "operator" : "mobile", "user_type" : "tourist", "create_timestamp" : 1499689306, "update_timestamp" : 1499689306 }

上面的代码为数据格式 创建索引

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的前面,否则查询不出数据

yii2中使用

$q = new \yii\mongodb\Query(); $q->from('user'); $q->andWhere(['disabled'=>'1'])->andWhere(['user_type'=>'normal']); $q->limit(1)->offset(2)->orderBy(['status'=>1]); $count = $q->count(); $dataList = $q->all(); $data = $q->one();

除聚合外,大部分查询和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);
转载请注明原文地址: https://www.6miu.com/read-37925.html

最新回复(0)