Ubuntu下MongoDB的安装和使用

MongoDB安装很简单,无需下载源文件,可以直接用apt-get命令进行安装。 

打开终端,输入以下命令:

sudoapt-get install mongodb

截图如下: 

《Ubuntu下MongoDB的安装和使用》

安装完成后,在终端输入以下命令查看MongoDB版本:

mongo -version

输出版本信息,表明安装成功,截图如下: 

《Ubuntu下MongoDB的安装和使用》

启动和关闭mongodb命令如下:

service mongodb start

service mongodb stop

截图如下: 

《Ubuntu下MongoDB的安装和使用》

默认设置MongoDB是随Ubuntu启动自动启动的。 

输入以下命令查看是否启动成功:

pgrep mongo-l#注意:-l是英文字母l,不是阿拉伯数字1

截图如下: 

《Ubuntu下MongoDB的安装和使用》

卸载MongoDB

sudoapt-get –purge remove mongodb mongodb-clients mongodb-server

二. 重启系统以后mongo程序要自己重新手动启动,步骤如下:

1.运行“locate mongo”命令查看系统默认把mongo装到了哪里,这里主要关注三个东西.

(1)一个是名为“mongod”的程序的位置(他相当于mongo数据库的Server,需要一直在后台运行,我的路径:/usr/bin/mongod);

(2)一个是mongo 数据库log日志文件的位置(log日志文件要查看到具体的文件名,具体用法在后面有介绍,我的路径:/var/log/mongodb/mongodb.log);

(3)一个是mongo的log日志的位置(我的路径:/var/log/mongodb/mongodb.log)。

《Ubuntu下MongoDB的安装和使用》
《Ubuntu下MongoDB的安装和使用》

2.先进入mongod所在的目录(/usr/bin/mongod),然后运行“./mongod –dbpath /var/lib/mongodb/ –logpath /var/log/mongodb/mongodb.log –logappend &

–dbpath:指定mongo的数据库文件在哪个文件夹

–logpath:指定mongo的log日志是哪个,这里log一定要指定到具体的文件名

–logappend:表示log的写入是采用附加的方式,默认的是覆盖之前的文件

&:表示程序在后台运行

《Ubuntu下MongoDB的安装和使用》

注意:如果是系统非正常关闭,这样启动会报错,由于mongodb自动被锁上了,这是需要进入mongodb数据库文件所在的目录(/var/lib/mongodb/),删除目录中的mongodb.lock文件,然后再进行上述操作。

《Ubuntu下MongoDB的安装和使用》

三、使用MongoDB

shell命令模式

输入mongo进入shell命令模式,默认连接的数据库是test数据库,在此之前一定要确保你已经启动了MongoDB,否则会出现错误,启动之后运行成功,如下截图: 

《Ubuntu下MongoDB的安装和使用》

常用操作命令:

数据库相关 

show dbs:显示数据库列表 

show collections:显示当前数据库中的集合(类似关系数据库中的表table) 

show users:显示所有用户 

use yourDB:切换当前数据库至yourDB 

db.help() :显示数据库操作命令 

db.yourCollection.help() :显示集合操作命令,yourCollection是集合名 

MongoDB没有创建数据库的命令,如果你想创建一个“School”的数据库,先运行use School命令,之后做一些操作(如:创建聚集集合db.createCollection(‘teacher’)),这样就可以创建一个名叫“School”的数据库。截图如下: 

《Ubuntu下MongoDB的安装和使用》

下面以一个School数据库为例,在School数据库中创建两个集合teacher和student,并对student集合中的数据进行增删改查基本操作(集合Collection相当于关系型数据库中的表table)。 

1、切换到School数据库

use School#切换到School数据库。MongoDB 无需预创建School数据库,在使用时会自动创建

2、创建Collection

db.createCollection(‘teacher’)#创建一个聚集集合。MongoDB 其实在插入数据的时候,也会自动创建对应的集合,无需预定义集合

截图如下: 

《Ubuntu下MongoDB的安装和使用》

3、插入数据 

与数据库创建类似,插入数据时也会自动创建集合。 

插入数据有两种方式:insert和save。

db.student.insert({_id:1, sname:’zhangsan’, sage:20})#_id可选db.student.save({_id:1, sname:’zhangsan’, sage:22})#_id可选

这两种方式,其插入的数据中_id字段均可不写,会自动生成一个唯一的_id来标识本条数据。而insert和save不同之处在于:在手动插入_id字段时,如果_id已经存在,insert不做操作,save做更新操作;如果不加_id字段,两者作用相同都是插入数据。截图如下: 

《Ubuntu下MongoDB的安装和使用》

添加的数据其结构是松散的,只要是bson格式均可,列属性均不固定,根据添加的数据为准。先定义数据再插入,就可以一次性插入多条数据,截图如下: 

《Ubuntu下MongoDB的安装和使用》

运行完以上例子,student 已自动创建,这也说明 MongoDB 不需要预先定义 collection ,在第一次插入数据后,collection 会自动的创建。截图如下: 

《Ubuntu下MongoDB的安装和使用》

3、查找数据 

db.youCollection.find(criteria, filterDisplay) 

criteria :查询条件,可选 

filterDisplay:筛选显示部分数据,如显示指定列数据,可选(当选择时,第一个参数不可省略,若查询条件为空,可用{}做占位符,如下例第三句)

db.student.find()#查询所有记录。相当于:select * from studentdb.student.find({sname:’lisi’})#查询sname=’lisi’的记录。相当于: select * from student where sname=’lisi’db.student.find({},{sname:1, sage:1})#查询指定列sname、sage数据。相当于:select sname,sage from student。sname:1表示返回sname列,默认_id字段也是返回的,可以添加_id:0(意为不返回_id)写成{sname: 1, sage: 1,_id:0},就不会返回默认的_id字段了db.student.find({sname:’zhangsan’, sage:22})#and 与条件查询。相当于:select * from student where sname = ‘zhangsan’ and sage = 22db.student.find({$or: [{sage:22}, {sage:25}]})#or 条件查询。相当于:select * from student where sage = 22 or sage = 25

查询操作类似,这里只给出db.student.find({sname: ‘lisi’})查询的截图,如下: 

《Ubuntu下MongoDB的安装和使用》

4、修改数据 

db.youCollection.update(criteria, objNew, upsert, multi ) 

criteria: update的查询条件,类似sql update查询内where后面的 

objNew : update的对象和一些更新的操作符(如$set)等,也可以理解为sql update查询内set后面的。 

upsert : 如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。 

multi: mongodb默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。默认false,只修改匹配到的第一条数据。 

其中criteria和objNew是必选参数,upsert和multi可选参数 

举例如下:

db.student.update({sname:’lisi’}, {$set: {sage:30}},false,true)#相当于:update student set sage =30 where sname = ‘lisi’;

操作截图如下: 

《Ubuntu下MongoDB的安装和使用》

5、删除数据

db.student.remove({sname:’chenliu’})#相当于:delete from student where sname=’chenliu’

1

操作截图如下: 

《Ubuntu下MongoDB的安装和使用》

6、退出shell命令模式 

输入exit或者Ctrl+C退出shell命令模式

注意:MongoDB相较安全性更偏向易用性,默认是没有开启用户权限的,如果想开启用户权限,可以参考Ubuntu下开启MongoDB用户权限

Java API编程实例

第一步:下载Java MongoDB Driver驱动jar包,Java MongoDB Driver下载地址,默认的下载目录为~/下载或者~/Downloads 

第二步:打开Eclipse,新建Java Project,新建Class,引入刚刚下载的jar包 

第三步:编码实现 

下面是源代码:

importjava.util.ArrayList;importjava.util.List;importorg.bson.Document;importcom.mongodb.MongoClient;importcom.mongodb.client.MongoCollection;importcom.mongodb.client.MongoCursor;importcom.mongodb.client.MongoDatabase;importcom.mongodb.client.model.Filters;publicclassTestMongoDB{/**    * @paramargs    */publicstaticvoidmain(String[] args) {        insert();//插入数据。执行插入时,可将其他三句函数调用语句注释掉,下同//      find(); //查找数据//      update();//更新数据//      delete();//删除数据}/**    * 返回指定数据库中的指定集合    * @paramdbname 数据库名    * @paramcollectionname 集合名    * @return*///MongoDB无需预定义数据库和集合,在使用的时候会自动创建publicstaticMongoCollectiongetCollection(String dbname,String collectionname){//实例化一个mongo客户端,服务器地址:localhost(本地),端口号:27017MongoClient  mongoClient=newMongoClient(“localhost”,27017);//实例化一个mongo数据库MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);//获取数据库中某个集合MongoCollection collection = mongoDatabase.getCollection(collectionname);returncollection;    }/**

    * 插入数据

    */publicstaticvoidinsert(){try{//连接MongoDB,指定连接数据库名,指定连接表名。MongoCollection collection= getCollection(“test”,”student”);//实例化一个文档,文档内容为{sname:’Mary’,sage:25},如果还有其他字段,可以继续追加appendDocument doc1=newDocument(“sname”,”Mary”).append(“sage”,25);//实例化一个文档,文档内容为{sname:’Bob’,sage:20}Document doc2=newDocument(“sname”,”Bob”).append(“sage”,20);            List documents =newArrayList();//将doc1、doc2加入到documents列表中documents.add(doc1);            documents.add(doc2);//将documents插入集合collection.insertMany(documents);              System.out.println(“插入成功”);        }catch(Exception e){            System.err.println( e.getClass().getName() +”: “+ e.getMessage() );        }    }/**

    * 查询数据

    */publicstaticvoidfind(){try{            MongoCollection collection = getCollection(“test”,”student”);//通过游标遍历检索出的文档集合 //          MongoCursor  cursor= collection.find(new Document(“sname”,”Mary”)). projection(new Document(“sname”,1).append(“sage”,1).append(“_id”, 0)).iterator();  //find查询条件:sname=’Mary’。projection筛选:显示sname和sage,不显示_id(_id默认会显示)//查询所有数据MongoCursor  cursor= collection.find().iterator();while(cursor.hasNext()){                System.out.println(cursor.next().toJson());            }        }catch(Exception e){            System.err.println( e.getClass().getName() +”: “+ e.getMessage() );        }    }/**

    * 更新数据

    */publicstaticvoidupdate(){try{            MongoCollection collection = getCollection(“test”,”student”);//更新文档  将文档中sname=’Mary’的文档修改为sage=22  collection.updateMany(Filters.eq(“sname”,”Mary”),newDocument(“$set”,newDocument(“sage”,22)));              System.out.println(“更新成功!”);        }catch(Exception e){            System.err.println( e.getClass().getName() +”: “+ e.getMessage() );        }    }/**

    * 删除数据

    */publicstaticvoiddelete(){try{            MongoCollection collection = getCollection(“test”,”student”);//删除符合条件的第一个文档  collection.deleteOne(Filters.eq(“sname”,”Bob”));//删除所有符合条件的文档  //collection.deleteMany (Filters.eq(“sname”, “Bob”));System.out.println(“删除成功!”);        }catch(Exception e){            System.err.println( e.getClass().getName() +”: “+ e.getMessage() );        }    }}

每次执行完程序,都可以返回shell模式查看结果。如:在eclipse执行完更新操作后,在shell模式输入db.student.find(),可以查看student集合的所有数据,截图如下: 

《Ubuntu下MongoDB的安装和使用》

    原文作者:泪滴在琴上
    原文地址: https://www.jianshu.com/p/802ad6be09bb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞