mongodb 探索

先下个mongodb,我的机器是64位所以下了64位的,一直点击安装,本来以为会弹出提示让我选择安装目录的,结果没提示应该是因为我选的是custom安装所以默认装到C盘program files下,但是没关系,我可以将数据库数据之类放到我想放的地方


一、启动
 为了能够从window服务中直接启动mongo而不用每次敲命令
c:\Program Files\MongoDB\Server\3.0\bin>mongod.exe --logpath F:\mongodb\log\mong
odb.log --logappend --dbpath F:\mongodb\db --directoryperdb --serviceName MongoD

B --nohttpinterface --auth --install 

指定serviceName为MongoDB

如果dbpath中有空格需要将其用双引号引起来 这样在查看本地服务中就可以看到MongoDB名称的服务

要正常退出需要ctrl+c,中间我估计没有正常退出,所以下次启动时命令行出现闪退,服务里面说不能启动,总之一句话启动不正常刚开始将db中的.lock文件删除,还是不行,最后干脆全部删除,再启动ok


二 权限

开启MongoDB服务时不添加任何参数时,默认是没有权限验证的,登录的用户可以对数据库任意操作而且可以远程访问数据,但是我启动时增加了--auth参数所以需要权限验证。否则没有权限执行大部分命令。mongodb是没有默认管理员账号,所以要先添加管理员账号,再开启权限认证。将原先服务关闭重新开启服务(将--auth参数先去掉) mongod.exe --logpath F:\mongodb\log\mongodb.log --logappend --dbpath F:\mongodb\db --directoryperdb --serviceName MongoDB --nohttpinterface

关于mongodb的权限有以下几个注意点
1,mongodb是没有默认管理员账号,所以要先添加管理员账号,再开启权限认证。
2,切换到admin数据库,添加的账号才是管理员账号。
3,用户只能在用户所在数据库登录,包括管理员账号。
4,管理员可以管理所有数据库,但是不能直接管理其他数据库,要先在数据库认证后才可以。

这应该算是权限机制吧,感觉比mysql等更安全

先切换admin数据库创建一个管理员账号
 >use admin
>db.createUser({user:"test",pwd:"123456",roles:[{role:"userAdminAnyDatabase",db:"admin"}]}) //创建一个管理账号
>use test
 > db.createUser({user:"test",pwd:"123456",roles:[{role:"readWrite",db:"test"},{role:"read",db:"test"}]})//为test库创建一个读写权限账号

>db.auth('test','123456')//返回1验证通过,我理解应该为以该账号登陆,不登陆就不能做相关操作。所以每次重新进该库都要验证下

验证过后就来看下具体操作吧

三、具体操作

//插入数据  以person集合为例
db.person.insert({"name":"jack","age":20})
//查询find操作
db.person.find()//我理解相当于select * from person
db.person.find({"name":"jack"})
db.person.find({"name":"joe"})
日常开发中用的最多的1、>, >=, <, <=, !=, = 2、And,OR,In,NotIn
对应mongodb
1、"$gt", "$gte", "$lt", "$lte", "$ne"
 db.person.find({"age":{$gt:22}}) 

2、&& "$or", "$in","$nin"
 &&
> db.person.find({"name":"joe","age":30})
{ "_id" : ObjectId("55b5ed572fdb9660da8571cf"), "name" : "joe", "age" : 30 } 
$or
> db.person.find({$or:[{"name":"joe"},{"age":20}]})
{ "_id" : ObjectId("55b5ed572fdb9660da8571cf"), "name" : "joe", "age" : 30 } 
 $in

> db.person.find({"name":{$in:["jack","joe"]}})
{ "_id" : ObjectId("55b5ed572fdb9660da8571cf"), "name" : "joe", "age" : 30 }
$nin 
> db.person.find({"name":{$nin:["jack","joe"]}})

 3、正则表达式匹配,我正则不强,算了吧,再说效率也是个问题,能不用正则表达式的就不要用

 4、$where 可以定义个function查讯复杂的业务语句
 > db.person.find({$where:function(){return this.name=='joe'}})
{ "_id" : ObjectId("55b5ed572fdb9660da8571cf"), "name" : "joe", "age" : 30 }
 

//更新update操作db.collection.update(queryupdateoptions)options//默认为1, If true, then when an update statement fails, return without performing the remaining update statements. If false, then when an update fails, continue with the remaining update statements, if any. Defaults to true
query为条件,update为更新的字段
> db.person.update({"name":"jack"},{"name":"jack","age":30})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.person.update({"name":"jack"},{"name":"joe","age":20})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.person.find()
{ "_id" : ObjectId("55b5ed572fdb9660da8571cf"), "name" : "joe", "age" : 20 }

> db.person.update({"name":"jack"},{"name":"joe","age":20})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })

看出区别了吗,第一个json对象相当于条件,第二个相当于update的字段

> db.person.update({"name":"joe"},{"age":30})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

以上为对某些字段的更新以下为全部更新

> var model=db.person.findOne({"name":"joe"})
> model.age=20
20
> db.person.findOne({"name":"joe"})//findOne相当于limit 1
{ "_id" : ObjectId("55b5ed572fdb9660da8571cf"), "name" : "joe", "age" : 30 }
>
> db.person.update({"name":"joe"},model)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.person.findOne({"name":"joe"})
{ "_id" : ObjectId("55b5ed572fdb9660da8571cf"), "name" : "joe", "age" : 20 }

//删除remove操作
db.collection.remove(<query>,{ justOne:<boolean>,writeConcern:<document>})//justOne 默认false即满足条件全部删除,remove()不带任何参数将删除该集合所有数据,很危险的操作,在mongo中是不可撤回的操作,三思而后行

 四、聚合
> db.person.count()
1
> db.person.count({"name":"jack"})//name条件

0
> db.person.distinct("age")//指定了谁,谁就不能重复
[ 20 ] 
group
{
  group:
   {
     ns: <namespace>,
     key: <key>,
     $reduce: <reduce function>,
     $keyf: <key function>,
     cond: <query>,
     finalize: <finalize function>
   }
}
initial: initializes the aggregation result document
key: the field or fields to group.returns a "key object" for use as the grouping key
reduce:An aggregation function that operates on the documents during the grouping operation. These functions may return a sum or a count. The function takes two arguments: the current document and an aggregation result document for that group
这个函数的第一个参数是当前的文档对象,第二个参数是上一次function操作的累计对象
cond:The selection criteria to determine which documents in the collection to process. If you omit the cond field, group processes all the documents in the collection for the group operation    //过滤条件
finalize: A function that runs each item in the result set before groupreturns the final value. This function can either modify the result document or replace the result document as a whole. Unlike the $keyf and $reducefields that also specify a function, this field name is finalizenot$finalize.//
> db.persons.group({"key":{"age":true},"initial":{"person":[]},"$reduce":functio
n(cur,prev){prev.person.push(cur.name);}})
[
        {
                "age" : 20,
                "person" : [
                        "jack",
                        "hary"
                ]
        },
        {
                "age" : 25,
                "person" : [
                        "cherry",
                        "orient",
                        "jun"
                ]
        },
        {
                "age" : 30,
                "person" : [
                        "juan"
                ]
        }
]
>
//取group后age<=25的集合
 > db.persons.group({"key":{"age":'a'},"initial":{"person":[]},"$reduce":function
(cur,prev){prev.person.push(cur.name);},"cond":{"age":{$lte:25}}})
[
        {
                "age" : 20,
                "person" : [
                        "jack",
                        "hary"
                ]
        },
        {
                "age" : 25,
                "person" : [
                        "cherry",
                        "orient",
                        "jun"
                ]
        }
]
//对分组里面的数据进行count下,看每组有多少人  finalize参数的作用
> db.persons.group({"key":{"age":'a'},"initial":{"person":[]},"$reduce":function
(cur,prev){prev.person.push(cur.name);},"finalize":function(out){out.count=out.p
erson.length},"cond":{"age":{$lte:25}}})
[
        {
                "age" : 20,
                "person" : [
                        "jack",
                        "hary"
                ],
                "count" : 2
        },
        {
                "age" : 25,
                "person" : [
                        "cherry",
                        "orient",
                        "jun"
                ],
                "count" : 3
        }
]
>
>

五、游标 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值