1.官网下载安装介质:https://www.mongodb.com/download-center,选择适当的版本,这里以linux版本为例;
2.解压到系统某路径, tar -xvzf mongodb-linux-x86_64-rhel70-3.4.10.tgz
并在安装目录创建data目录,以及logs目录和logs/mongodb.log文件
3.使用vim在mongodb的bin目录创建mongodb的配置文件,如:vim bin/mongodb.conf,mongodb.conf内容如下:注意配置文件中的空格,隔行三个空格。
其他的配置文件可参考官网介绍https://docs.mongodb.com/manual/reference/configuration-options/
storage:
dbPath: "/usr/local/mongodb-3.4.10/data"
systemLog:
destination: file
path: "/usr/local/mongodb-3.4.10/logs/mongodb.log"
net:
port: 27022
http:
RESTInterfaceEnabled: true
processManagement:
fork: false
4.在mongdb的bin目录编写shell脚本,命名为start-mongodb.sh,并赋权chmod 777 start-mongodb.sh
脚本内容如下:
nohup ./mongod -f mongodb.conf &
5.使用start-mongodb.sh启动mongodb实例,如:./start-mongodb
6.使用mongoClient进行测试,./mongo localhost:27022
7.自己玩的话关闭linux的防火墙吧systemctl disable firewalld.service
8.使用官方自带的图形化管理工具MongoDB Compass Community去连接mongodb更加直观,也可以使用robo3t ,https://robomongo.org/download,这个工具是可以执行脚本的。
常用api
> show dbs //查看数据库
admin 0.000GB
lison 0.000GB
local 0.000GB
> use wen //使用wen数据库
switched to db wen
> show collections //查看wen数据库中的集合(表)
users
wen
> db.wen.find().pretty() ; //查看wen这个集合(表)中的数据,.pretty()方法可以使得数据更加直观
> db.wen.find({"username":{"$in":["chen","sean"]}})//查询username是chen和sean的人
> db.wen.find({"lenght":{"$lt":1.77}});//查询lenght小于1.77的数据
> db.wen.find({"lenght":{"$not":{"$gte":1.77}}}).pretty() //查询没有lenght和lenght大于1.77的数据
> db.wen.find({"lenght":{"$exists":false}}).pretty()//查询没有lenght字段的数据
> db.wen.find({},{"favorites":0}).pretty() //不显示favorites字段,值是1的时候是显示
> db.wen.find().pretty().sort({"age":-1})//按照age排序,-1是倒叙,1是正序
> db.wen.find().pretty().sort({"age":-1}).limit(1)//只显示1条
> db.wen.find().pretty().sort({"age":-1}).limit(1).skip(2)//跳过两条只显示1条
兼容性
建议使用版本:
spring版本:4.3.14.RELEASE
mongo-java-driver:3.6.0
spring-data-mongodb :1.10.9.RELEASE
org.mongodb
mongo-java-driver
3.6.0
org.springframework.data
spring-data-mongodb
1.10.9.RELEASE
1.java document方式的API(mongodb提供的原生api)
package com.dongnao.mongo.test;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import static com.mongodb.client.model.Updates.*;
import static com.mongodb.client.model.Filters.*;
//原生java驱动 document的操作方式
public class QuickStartJavaDocTest {
private static final Logger logger = LoggerFactory.getLogger(QuickStartJavaDocTest.class);
private MongoDatabase db;
//collection对应的是表 document对应的是表中的一条数据,如果过pojo就可以吧document换成pojo
private MongoCollection collection;
private MongoClient client;
@Before
public void init(){
client = new MongoClient("192.168.124.151",27022);
db =client.getDatabase("lison");
collection = db.getCollection("users");
}
@Test
public void insertDemo(){
Document doc1 = new Document();
doc1.append("username", "cang");
doc1.append("country", "USA");
doc1.append("age", 20);
doc1.append("lenght", 1.77f);
doc1.append("salary", new BigDecimal("6565.22"));
Map address1 = new HashMap();
address1.put("aCode", "0000");
address1.put("add", "xxx000");
doc1.append("address", address1);
Map favorites1 = new HashMap();
favorites1.put("movies", Arrays.asList("aa","bb"));
favorites1.put("cites", Arrays.asList("东莞","东京"));
doc1.append("favorites", favorites1);
Document doc2 = new Document();
doc2.append("username", "chen");
doc2.append("country", "China");
doc2.append("age", 30);
doc2.append("lenght", 1.77f);
doc2.append("salary", new BigDecimal("8888.22"));
Map address2 = new HashMap<>();
address2.put("aCode", "411000");
address2.put("add", "我的地址2");
doc1.append("address", address2);
Map favorites2 = new HashMap<>();
favorites2.put("movies", Arrays.asList("东游记","一路向东"));
favorites2.put("cites", Arrays.asList("珠海","东京"));
doc2.append("favorites", favorites2);
collection.insertMany(Arrays.asList(doc1,doc2));
}
@Test
public void testDelete(){
//delete from users where username = ‘lison’
DeleteResult deleteMany = collection.deleteMany(eq("username", "lison"));
logger.info(String.valueOf(deleteMany.getDeletedCount()));
//delete from users where age >8 and age <25
DeleteResult deleteMany2 = collection.deleteMany(and(gt("age",8),lt("age",25)));
logger.info(String.valueOf(deleteMany2.getDeletedCount()));
}
@Test
public void testUpdate(){
//update users(age,username) set (6,"yang") where username = 'lison'
Document document=new Document();
document.append("username","yang");
document.append("age",100);
UpdateResult updateMany = collection.updateMany(eq("username", "chen"),
new Document("$set",document));
logger.info(String.valueOf(updateMany.getModifiedCount()));
//update users set favorites.movies add "小电影2 ", "小电影3" where favorites.cites has "东莞"
UpdateResult updateMany2 = collection.updateMany(eq("favorites.cites", "东莞"),
addEachToSet("favorites.movies", Arrays.asList( "小电影2 ", "小电影3")));
logger.info(String.valueOf(updateMany2.getModifiedCount()));
}
@Test
public void testFind(){
final List ret = new ArrayList<>();
Block printBlock = new Block() {
@Override
public void apply(Document t) {
logger.info(t.toJson());
ret.add(t);
}
};
//select * from users where favorites.cites has "东莞"、"东京"
FindIterable find = collection.find(all("favorites.cites", Arrays.asList("东莞","东京")));
find.forEach(printBlock);
logger.info(String.valueOf(ret.size()));
ret.removeAll(ret);
//select * from users where username like '%s%' and (contry= English or contry = USA)
String regexStr = ".*s.*";
Bson regex = regex("username", regexStr);
Bson or = or(eq("country","English"),eq("country","USA"));
FindIterable find2 = collection.find(and(regex,or));
find2.forEach(printBlock);
logger.info(String.valueOf(ret.size()));
}
}
2.java pojo的方式(mongo-java-driver:3.5.0开始支持)
package com.dongnao.mongo.test;
import static com.mongodb.client.model.Updates.*;
import static com.mongodb.client.model.Filters.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dongnao.mongo.entity.Address;
import com.dongnao.mongo.entity.Favorites;
import com.dongnao.mongo.entity.User;
import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
//原生java驱动 Pojo的操作方式
public class QuickStartJavaPojoTest {
private static final Logger logger = LoggerFactory.getLogger(QuickStartJavaPojoTest.class);
private MongoDatabase db;
private MongoCollection doc;
private MongoClient client;
@Before
public void init(){
//编解码器的list(编解码器就是用来吧java的数据类型和mongodb的数据类型关联起来)
List codecResgistes = new ArrayList<>();
//编解码器的list加入默认的编解码器集合
codecResgistes.add(MongoClient.getDefaultCodecRegistry());
//生成一个pojo的编解码器
CodecRegistry pojoProviders = CodecRegistries.
fromProviders(PojoCodecProvider.builder().automatic(true).build());
codecResgistes.add(pojoProviders);
//通过编解码器的list生成编解码器注册中心
CodecRegistry registry = CodecRegistries.fromRegistries(codecResgistes);
//把编解码器注册中心放入MongoClientOptions,MongoClientOptions是定义连接池的
MongoClientOptions build = MongoClientOptions.builder().
codecRegistry(registry).build();
ServerAddress serverAddress = new ServerAddress("192.168.124.151",27022);
client = new MongoClient(serverAddress, build);
// client = new MongoClient("192.168.1.142",27022);
db =client.getDatabase("lison");
doc = db.getCollection("users",User.class);
}
@Test
public void insertDemo(){
User user = new User();
user.setUsername("cang");
user.setCountry("USA");
user.setAge(20);
user.setLenght(1.77f);
user.setSalary(new BigDecimal("6265.22"));
Address address1 = new Address();
address1.setaCode("411222");
address1.setAdd("sdfsdf");
user.setAddress(address1);
Favorites favorites1 = new Favorites();
favorites1.setCites(Arrays.asList("东莞","东京"));
favorites1.setMovies(Arrays.asList("西游记","一路范德萨范德萨范德萨西"));
user.setFavorites(favorites1);
User user1 = new User();
user1.setUsername("chen");
user1.setCountry("China");
user1.setAge(30);
user1.setLenght(1.77f);
user1.setSalary(new BigDecimal("6885.22"));
Address address2 = new Address();
address2.setaCode("411000");
address2.setAdd("我的地址2");
user1.setAddress(address2);
Favorites favorites2 = new Favorites();
favorites2.setCites(Arrays.asList("珠海","东京"));
favorites2.setMovies(Arrays.asList("东游记","一路多少分付付付东"));
user1.setFavorites(favorites2);
doc.insertMany(Arrays.asList(user,user1));
}
@Test
public void testDelete(){
//delete from users where username = ‘lison’
DeleteResult deleteMany = doc.deleteMany(eq("username", "lison"));
logger.info(String.valueOf(deleteMany.getDeletedCount()));
//delete from users where age >8 and age <25
DeleteResult deleteMany2 = doc.deleteMany(and(gt("age",8),lt("age",25)));
logger.info(String.valueOf(deleteMany2.getDeletedCount()));
}
@Test
public void testUpdate(){
//update users set age=6 where username = 'lison'
User user=new User();
user.setAddress(new Address("fdsafdsa","dfsadfsa"));
UpdateResult updateMany = doc.updateMany(eq("username", "cang"),
new Document("$set",user));
logger.info(String.valueOf(updateMany.getModifiedCount()));
//update users set favorites.movies add "小电影2 ", "小电影3" where favorites.cites has "东莞"
UpdateResult updateMany2 = doc.updateMany(eq("favorites.cites", "东莞"),
addEachToSet("favorites.movies", Arrays.asList( "小电影2 ", "小电影3")));
logger.info(String.valueOf(updateMany2.getModifiedCount()));
}
@Test
public void testFind(){
final List ret = new ArrayList<>();
Block printBlock = new Block() {
@Override
public void apply(User t) {
// logger.info();
System.out.println(t.getUsername());
System.out.println(t.getSalary());
ret.add(t);
}
};
//select * from users where favorites.cites has "东莞"、"东京"
FindIterable find = doc.find(all("favorites.cites", Arrays.asList("东莞","东京")));
find.forEach(printBlock);
logger.info(String.valueOf(ret.size()));
ret.removeAll(ret);
//select * from users where username like '%s%' and (contry= English or contry = USA)
String regexStr = ".*s.*";
Bson regex = regex("username", regexStr);
Bson or = or(eq("country","English"),eq("country","USA"));
FindIterable find2 = doc.find(and(regex,or));
find2.forEach(printBlock);
logger.info(String.valueOf(ret.size()));
}
}
如果collection中的数据格式比较固定推荐使用spring-data-mongodb,或者pojo的方式开发,如果非常不固定,还是推荐使用mongodb提供的java原生api。