MongoDB安装与测试

MongoDB安装与测试

1.下载MongoDB,选定windows版本
MongoDB下载地址
JDBC下载地址
2.安装
2.1 运行“mongodb-win32-x86_64-2008plus-ssl-3.4.5-signed.msi”安装MongoDB。
2.2 安装完成后,进入安装目录下的bin目录,建立批处理文件mongod.bat,内容如下(其中“d:\dbpart\MongoDB\db”为数据目录,可根据实际情况自行更改):

mongod.exe --dbpath=d:\dbpart\MongoDB\db --directoryperdb  --logpath d:\dbpart\MongoDB\logs.txt --logappend

说明:日志文件为d:\dbpart\MongoDB\logs.txt,以及添加方式记录(追加–logappend)。
数据目录为d:\dbpart\MongoDB\db,并且每个数据库将储存在一个单独的目录(–directoryperdb)。
2.3 然后建立数据库目录“d:\dbpart\MongoDB\db”,CMD进入安装目录下的bin目录,执行批命令:mongod.bat(当然也可以将上述命令自己敲一遍)。如下图所示:
这里写图片描述
2.4 这时,在我们建立的数据库目录“d:\dbpart\MongoDB\db”中可以看到出现了许多文件夹及文件,如下图所示:
这里写图片描述
2.5 测试时,服务器端要一直运行。

3.客户端
3.1启动客户端
再打开一个CMD窗口,执行安装目录下的bin目录中的mongo.exe,如下图所示:
这里写图片描述
说明
shell会在启动时自动连接MongoDB服务器,默认连接test数据库,并将这个数据库连接赋值给全局变量db,这个变量是MongoDB的主要入口点。shell是功能完备的JavaScript解释器,可以运行任何javascript程序。
MongoDB使用GridFS来储存大文件。每个BSON对象大小不能超过4MB。
字段名限制:不能以“$”开头;不能包含“.”;“_id”是系统保留的字段,但用户可以自己储存唯一性的数据在字段中。
MongoDB为每个数据库分配一系列文件。每个数据文件都会被预分配一个大小,第一个文件名字为“.0”,大小为64MB,第二个文件“.1”为128MB,依此类推,文件大小上限为2GB。如下:

3.2查询系统数据库
show dbs // 列出所有数据库
admin:从权限角度来看,这是‘root’数据库.要是将一个用户添加到这个数据库,这个用户自动继承所有数据库的权限。有些服务器命令也只能从这个数据库运行,如关闭服务器
local:这个数据库永远不会被复制,可以用来存储于本地单台服务器的任意集合
这里写图片描述
3.2新建数据库
use person // 使用数据库person。即使这个数据库不存在也可以执行,但该数据库不会立刻被新建,要等到执行了insert等的操作时,才会建立这个数据库。但是直接离开的话,这个数据库会被mongo删除。
3.3 插入数据
db.person.insert({name:”zhang_3”,age:20,address:”xi_an”});
db.person.insert({name:”li_4”,age:30,address:”si_chuan”});
db.person.insert({name:”wang_2”,age:40,address:”tai_wan”});
这里写图片描述
3.4 查询数据
db.person.find()
db.person.find({age:{$gte:30}})
db.person.findOne()
这里写图片描述
lt>lessthen lte ->less than and equal 不大于
gt>greaterthen gte ->greater then and equal 不小于
ne>notequal or -> 关系或
$and -> 关系与

3.5 修改数据
db.person.update({name:”zhang_3”},{set:{age:25}})  
db.person.update({name:”zhang_3”},{
set:{age:25,address:”xi_an_1”}})

3.6 删除数据
db.person.remove(修改条件)
如:
db.person.remove({name:”zhang_3”})

3.7 建索引:
db.person.ensureIndex({name:1}, {unique:true}) // 唯一索引

3.8 备份
mongodump -d person -o d:\dbpart\MongoDB\person
这里写图片描述
3.9 删除数据库
use person
// 查看集合
show collections
// 删除数据库
db.dropDatabase()

3.10 恢复
mongorestore -d person d:\dbpart\MongoDB\person\person\person.bson

4 使用java操作MongoDB
4.1 使用 com.mongodb.client.MongoDatabase 类中的createCollection()来创建集合

// 创建集合
public void testConnDB() {
    try {
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("连接MongoDB数据库成功");
        mongoDatabase.createCollection("test");
        System.out.println("集合创建成功");

        // 关闭连接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.2 选择集合

// 选择集合
public void getCollections() {
    try {
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("连接MongoDB数据库成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("person");
        System.out.println("集合 test 选择成功[" + collection.count() + "]");

        // 关闭连接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.3 使用com.mongodb.client.MongoCollection类的 insertMany() 方法来插入一个文档

// 插入文档
public void InsertDoc() {
    try {
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("Connect to database successfully");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 选择成功");
        // 插入文档
        /**
         * 1. 创建文档 org.bson.Document 参数为key-value的格式 2. 创建文档集合List<Document>
         * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>)
         * 插入单个文档可以用 mongoCollection.insertOne(Document)
         */
        Document document = new Document("title", "MongoDB").append("description", "database").append("likes", 100)
                .append("by", "Fly").append("memo", "插入中文");
        List<Document> documents = new ArrayList<Document>();
        documents.add(document);
        collection.insertMany(documents);
        System.out.println("文档插入成功");

        // 关闭连接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.4 使用 com.mongodb.client.MongoCollection 类中的 find() 方法来获取集合中的所有文档。

// 查询文档
public void qryDoc() {
    try {
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("连接MongoDB数据库成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 选择成功");

        // 检索所有文档
        /**
         * 1. 获取迭代器FindIterable<Document> 2. 获取游标MongoCursor<Document> 3.
         * 通过游标遍历检索出的文档集合
         */
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }

        // 关闭连接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.5 修改文档

// 修改文档
public void updDoc() {
    try {
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("连接MongoDB数据库成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 选择成功");

        // 更新文档 将文档中likes=100的文档修改为likes=200
        collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200)));
        // 检索查看结果
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }

        // 关闭连接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

4.6 删除文档

// 删除文档
public void delDoc() {
    try {
        // 连接到 mongodb 服务
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        // 连接到数据库
        MongoDatabase mongoDatabase = mongoClient.getDatabase("person");
        System.out.println("连接MongoDB数据库成功");

        MongoCollection<Document> collection = mongoDatabase.getCollection("test");
        System.out.println("集合 test 选择成功");

        // 删除符合条件的第一个文档
        collection.deleteOne(Filters.eq("likes", 200));
        // 删除所有符合条件的文档
        collection.deleteMany(Filters.eq("memo", "插入中文"));
        // 检索查看结果
        FindIterable<Document> findIterable = collection.find();
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next());
        }

        // 关闭连接
        mongoClient.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值