mongodb 高级语句

索引
  • 查看索引

    db.Ttest.getIndexes();
    #或
    db.getCollection('Ttest').getIndexes();
  • 新建索引
#给时间字段新建索引
db.Ttest.ensureIndex({"LTimeB":1})
查询
  • 嵌套数组进行分页查询

#Z118005 这个是嵌套数组
db.getCollection('Ttest').aggregate([{$match: {"_id": ObjectId("5a53136ae138237acab5c841")}},{$unwind:"$Z118005"},{$limit:10},{$skip:3}]).pretty();
#calls 这个是嵌套数组
db.getCollection('call_pool').aggregate([{$match: {"calls.category": "system"}},{$unwind:"$calls"}]).pretty()

#php 代码查询语句
$command = [['$unwind'=>'$calls'],['$match'=>['_id'=>$calls_id,'calls.category'=>$type]],['$limit'=>(int)$page]];
$data = $collection->aggregate($command);
  • 查询嵌套数组个数大于100组的数据id
db.getCollection('Ttest').find({"Z118005.100":{$exists:1}},{'_id':1});
  • 查询嵌套数组,指定筛选嵌套数组的前10条
db.Ttest.find({},{"Z118005":{"$slice":20}});

#查找条件是为271 ,只需要筛选 Z118005和total字段
db.Ttest.find({"total":271},{"Z118005":{"$slice":5},'total':1});
#find 方法中第一个大括号填写条件,第二个表示需要筛选的字段,1表示需要,0表示不需要
  • 查找 total存在且等于null的
db.Ttest.find({total: {"$in":[null],$exists: true}});  
#not in 不等于 array
db.Ttest.find({total: {"$nin":[null],$exists: true}}); 
#不等于 one
db.Ttest.find( { total: { $ne : 3 } } );
  • $mod 取模运算 查询 total取模 6 等于 1 的数据
db.ToperaSystem.find({total: {"$mod":[6,1]}});
  • 查询total大于等于并小于
db.ToperaSystem.find({total:{"$gte":100,"$lte":287}}); 
#php 代码 条件
 $where = [
    ['time'=>['$gte'=>$time_start, '$lte'=>$time_end]],
    ['_id'=>new MongoId($id)])]
];

 $where = [
 "$or"=>[
        ['time'=>['$gte'=>$time_start, '$lte'=>$time_end]],
        ['_id'=>new MongoId($id)])]
    ]
];
  • 查找 total 存在271,14的
#$in必须满足[]中的任意一值则可。
db.Ttest.find({total: {"$in":[14,143]}});
#本人亲自实践 $in 和 $all的不同  
# $all则必须满足[]中的所有值,简称完全匹配。
db.Ttest.find({total: {"$all":[14,143]}});
  • 排序的升序降序 分别有-1 和1标识
db.Ttest.find().sort({total: -1});
  • 模糊查找
db.Ttest.find({"title":/^F5\\(v/})
##php 语句
# 值的注意的是$keyword [1.^表示匹配输入字符串的开始位置 2.字符串中有元字符如'('需要转义 '\\']
 $where = ['title' => ['$in' => [new Regex("$keyword", 'i')]]];
  • -

新增数据库用户

#新加一个superman的用户操作admin超级库的,拥有全部权限
db.createUser(
  {
    user: "superman",
    pwd: "superman",
    roles: [ { role: "readWriteAnyDatabase", db: "admin" }, { role: "dbAdminAnyDatabase", db: "admin" }]
  }
)

#新建一个testuser用管理test数据库,拥有读写权限
db.createUser(
  {
    user: "testuser",
    pwd: "testuser",
    roles: [ { role: "readWrite", db: "test" }]
  }
)

修改mongodb支持远程连接

#不知道配置文件在哪里的同学
find / -name "mongod.conf"
#cd到对应目录
vi mongod.conf
#找到net模块
修改bindIp=192.168.1.6 #修改127.0.0.1这个本地地址为网络ip
#这里简单提一下 万一同学忘记了登录db的用户名等
#这个文件的下面security模块 就有作用了
authorization: "disabled"
#修改完记得重启
service mongod restart
#应用
启动方式
./bin/mongod -f mongod.conf 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值