Mongodb使用笔记
一、安装
- 下载地址:
https://www.mongodb.org/dl/win32/x86_64-2008plus-ssl?_ga=2.224499034.1937345960.1533433838-1304921847.1533433838 - 解压缩到自己想要安装的目录,比如d:\mongodb
- 创建文件夹d:\mongodb\db、d:\mongodb\log,分别用来安装db和日志文件,在log文件夹下创建一个日志文件MongoDB.log,即d:\mongodb\log\MongoDB.log
- 运行cmd.exe进入dos命令界面,执行下列命令
> cd d:\mongodb\bin
> d:\mongodb\bin>mongod -dbpath “d:\mongodb\db” - 测试链接。在浏览器中输入:http://localhost:27017
It looks like you are trying to access MongoDB over HTTP on the native driver port.表示启动成功 - 当mongod.exe被关闭时,mongo.exe 就无法连接到数据库了,因此每次想使用mongodb数据库都要开启mongod.exe程序,所以比较麻烦,此时我们可以将MongoDB安装为windows服务
cmd跳转到mongodb下的bin目录下输入
mongod --logpath d:\mongodb\log\mongodb.log --logappend --dbpath d:\mongodb\db --directoryperdb --serviceName MongoDB --install
二、使用Shell
继续输入:
mongo
如果是连接远程数据库:
mongo 192.168.1.200:27017/database -u user -p password
然后使用如下5个命令进行数据库的创建、查找
show dbs
use taskdb
db.task.insert({…})
show collections
db.task.find()
管理员:c:\windows\system32\cmd.exe - mongo
D:\mongodb\bin>mongo
MongoDB shell version v3.4.1
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.1
Welcome to the MongoDB shell.
For interactive help, type “help”.
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
2018-08-05T10:38:19.068+0800 I CONTROL [initandlisten]
2018-08-05T10:38:19.069+0800 I CONTROL [initandlisten] ** WARNING: Access contr
ol is not enabled for the database.
2018-08-05T10:38:19.070+0800 I CONTROL [initandlisten] ** Read and wri
te access to data and configuration is unrestricted.
2018-08-05T10:38:19.071+0800 I CONTROL [initandlisten]
2018-08-05T10:38:19.072+0800 I CONTROL [initandlisten] Hotfix KB2731284 or late
r update is not installed, will zero-out data files.
2018-08-05T10:38:19.073+0800 I CONTROL [initandlisten]
show dbs
admin 0.000GB
local 0.000GB
use taskdb
switched to db taskdb
db.task.insert({name:“第一个任务”,states:{name:“创建”,person:“Jim”}})
WriteResult({ “nInserted” : 1 })
show dbs
admin 0.000GB
local 0.000GB
taskdb 0.000GB
show collections
task
db.task.find()
{ “_id” : ObjectId(“5b66677231e557b59154c59f”), “name” : “第一个任务”, “states”
: { “name” : “创建”, “person” : “Jim” } }
三、java连接Mongodb
1、Maven添加依赖
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.4.1</version>
</dependency>
</dependencies>
2、连接数据库的Java代码如
import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
3、如果你的 Mongo 需要验证用户名及密码,可以使用以下代码:
package com.iwhere.rongyun.config;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
@Configuration
public class MongoConfig {
private static Logger LOGGER = LoggerFactory.getLogger(MongoConfig.class);
@Value("${mongodb.hostports}")
private String hostports;
@Value("${mongodb.maxConnect}")
private String maxConnect;
@Value("${mongodb.maxWaitThread}")
private String maxWaitThread;
@Value("${mongodb.maxTimeOut}")
private String maxTimeOut;
@Value("${mongodb.maxWaitTime}")
private String maxWaitTime;
@Value("${mongodb.username}")
private String username;
@Value("${mongodb.password}")
private String password;
@Value("${mongodb.database}")
private String database;
@Value("${mongodb.collection")
private String collection;
@Bean
public MongoClient mongoClient() {
MongoClient mongoClient = null;
MongoClientOptions.Builder build = new MongoClientOptions.Builder();
build.connectionsPerHost(Integer.valueOf(maxConnect));
build.threadsAllowedToBlockForConnectionMultiplier(Integer.valueOf(maxWaitThread));
build.connectTimeout(Integer.valueOf(maxTimeOut) * 1000);
build.maxWaitTime(Integer.valueOf(maxWaitTime) * 1000);
MongoClientOptions options = build.build();
try {
List<ServerAddress> addrs = new ArrayList<ServerAddress>();
for (String hostport : hostports.split(", *")) {
if (StringUtils.isBlank(hostport)) {
continue;
}
hostport = hostport.trim();
ServerAddress serverAddress = new ServerAddress(hostport.split(":")[0],Integer.valueOf(hostport.split(":")[1]));
addrs.add(serverAddress);
}
MongoCredential credential = MongoCredential.createScramSha1Credential(username, database, password.toCharArray());
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(credential);
mongoClient = new MongoClient(addrs,credentials, options);
LOGGER.info("【mongodb client】: mongodb客户端创建成功");
} catch (Exception e) {
LOGGER.error("【mongodb client】: mongodb客户端创建成功");
e.printStackTrace();
}
return mongoClient;
}
@Bean
public MongoDatabase mongoDatabase(MongoClient mongoClient) {
MongoDatabase mongoDatabase = mongoClient.getDatabase(database);
return mongoDatabase;
}
@Bean
public MongoCollection<Document> mongoCollection(MongoDatabase mongoDatabase) {
MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collection);
return mongoCollection;
}
}
通过spring配置文件注入所需的值即可, mondb.properties为:
mongodb.hostports=192.168.51.100:2,192.168.51.101:533,192.168.51.102:21
mongodb.maxConnect=50
mongodb.maxWaitThread=50
mongodb.maxTimeOut=60
mongodb.maxWaitTime=60
mongodb.username=name
mongodb.password=pass
mongodb.database=data
mongodb.collection=user_rongyun
4、创建集合、选择集合、插入文档、检索所有文档、更新结果、检索结果
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");
System.out.println("Connect to database successfully");
mongoDatabase.createCollection("test");
System.out.println("集合创建成功");
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");
List<Document> documents = new ArrayList<Document>();
documents.add(document);
collection.insertMany(documents);
System.out.println("文档插入成功");
//检索所有文档
/**
* 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());
}
//更新文档 将文档中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());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}