在Ubuntu下安装Mongdb,以及Mongdb基本操作命令,ubuntumongdb


Mongdb安装

sudo apt-get install mongodb

关闭/启动服务

 sudo service mongodb stop
 sudo service mongodb start

连接服务

mongo

数据类型:

 null                                   {"x":null}
   boolean                             {"x":true}
   数值                   {"x":3.14}   {"x":3}    
          可以转换   NumberInt("3")    NumberLong("3")
   字符串                              {"x":"hello"}
   日期                    {"x":new Date()}
   正则表达式          {"x":/hello/ig}
   数组:                    {"x":[1,2,3]}
   内嵌文档:{"x":{"foo":{bar}}}
   对象id:{"x":ObjectId()}
              _id是每个文档所必须的用来做索引,_id的默认类型是ObjectId
    _id是字符串类型,用_id查找的时候注意了
   二进制:
   代码:{"x":function(){}}

基本操作命令:

–创建数据库

use zzg

–创建数据库下的集合,可以看成是一个table

db.createCollection("Student");

–插入数据

db.Student.insert([{"_id":1,"name":"王力宏"},{"_id":2,"name":"刘德华"}]);

–查看数据

db.Student.find();
db.Student.find({"_id":{$lt:99}}); --where id<val
db.Student.find({"_id":{$lte:99}}); --where id<=val
db.Student.find({"_id":{$gt:1}}); --where id>val
db.Student.find({"_id":{$gte:1}}); --where id>=val

–删除数据

db.Student.remove({"_id":1});

里面放条件
–查看用户下的所用集合

 show collections;

–删除数据库下的集合

db.Student.drop();

Mongdb对大小写敏感

–更新操作
$set修改器,默认

db.Student.update({"_id":1},{"name":"xxx"});
db.Student.find();

–修改器
$inc

db.Student.insert({"_id":1,"url":"www.zzg.com","pageViews":1})
db.Student.update({"_id":1},{"$inc":{"pageViews":1}});

$set

db.Student.update({"_id":1},{"$set":{"url":"449301818@qq.com"}});

将url变成一个数组

db.Student.update({"_id":1},{"$set":{"url":["449301818@qq.com","449301818@163.com","449301818@110.com"]}});

删除键

db.Student.update({"_id":1},{"$unset":{"url":1}})

–数组修改器
$push 向数组中添加值,可能会出现重复的值

db.Student.update({"_id":1},{"$push":{"company":"sc"}});

$each

db.Student.update({"_id":1},{"$push":{"company":{"$each":["a1","a2","a3","a4"]}}});

$slice 指定最大的长度,它的值必须是负数,表示保留最后的n个值

db.Student.update({"_id":1},{"$push":{"company":{"$each":["c1","c2","c3","c4","c5","c6","c7"],"$slice":-10}}});

$pop从数组中删除一个元素 key:1 表示从数据的末尾开始 key=-1表示从头部开始

db.Student.update({"_id":1},{"$pop":{"company":1}});

$pull 从数组中删除匹配的值

db.Student.update({"_id":1},{"$pull":{"company":"a2"}});

接下来加一点点难度

db.Student.insert({
    "_id":99,
    "content":"zzg如何?",
    "comments":[
        {"comment":"好","count":0},
        {"comment":"很好","count":0},
        {"comment":"非常好","count":0},
    ]
})

–通过数组下表访问

db.Student.update({"_id":99},{"$inc":{"comments.1.count":1}});
db.Student.update({"comments.comment":"很好"},{"$set":{"comments.$.comment":"很很好"}});

–Mongdb默认每次只修改一个文档,如果要修改所有满足条件的记录,则需要在后面添加条件{multi:true}

db.Student.update({"comments.comment":"好"},{"$inc":{"comments.$.count":3}},{multi:true});
等同于
db.Student.update({"comments.comment":"好"},{"$inc":{"comments.$.count":3}},false,true);

下一解讲案例,欢迎大家光临

版权声明:本文为博主原创文章,未经博主允许不得转载。

相关内容