MongoDB開發基礎

MongoDB安裝java

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的配置文件,如:vimbin/mongodb.conf,mongodb.conf內容請見下一頁課件;
4. 編寫shell腳本,命名爲start-mongodb.sh,腳本內容以下:nohup ./mongod -f mongodb.conf &
5. 使用start-mongodb.sh啓動mongodb實例,如:./start-mongodb
6. 使用mongoClient進行測試  經過restAPI地址測試(端口加配置文件的端扣加1000)linux

 http://192.168.225.129:28022/listDatabases?text=1

鏈接客戶端命令  在bin下執行spring

./mongo localhost:27022

配置文件sql

storage:
    dbPath: "/usr/local/apache/mongoDB/mongodb-linux-x86_64-rhel70-3.4.10/data"
systemLog:
    destination: file
    path: "/usr/local/apache//mongoDB/mongodb-linux-x86_64-rhel70-3.4.10/logs/mongodb.log"
net:
    port: 27022
    http:
        RESTInterfaceEnabled: true
processManagement:
    fork: false

MongoDB配置文件詳解mongodb

 

快速入門shell

數據結構介紹數據庫

 人員信息apache

{
    "_id" : ObjectId("59f938235d93fc4af8a37114"),
    "username" : 「lison",
    "country" : "in11digo",
    "address" : {
        "aCode" : "郵編",
        "add" : "d11pff"
    },
    "favorites" : {
    "movies" : ["殺破狼2","1dushe","雷神1"],
    "cites" : ["1sh","1cs","1zz"]
    },
    "age" : 18,
    "salary":NumberDecimal("2.099"),
    "lenght" :1.79
}

需求描述json

 新增2人
 刪除
     delete from users where username = ‘lison’
     delete from users where age >8 and age <25
 修改
     update users set age=6 where username = lison'
     update users set favorites.movies add "小電影2 ", "小電影3" where favorites.cites has "東莞"
 查詢
     select * from users where favorites.cites has "東莞"、"東京"
     select * from users where username like '%s%' and (country= English or country= USA)vim

學習目標

 直觀感覺mongoDB的魅力
 mongo開發入門(原生、spring)
 開發框架版本選擇
 mongoDB數據類型全解析
 對nosql的理念有初步的認識

mongoDB  客戶端 & 圖形化界面

 mongoDB自帶的命令客戶端 mongo
 mongoDB自帶的圖形化客戶端:Compass Community
 第三方mongoDB的圖形化客戶端:robomongo

原生java客戶端

 pom文件

<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.5.0</version>
</dependency>

Tips:
1. 3.5.0最新版本加入了對pojo的支持;
2. 3.5.0最新版本加強對json的支持;
3. mongodb原生客戶端支持兩種document和pojo模式的開發;

//原生java驅動 document的操做方式
public class QuickStartJavaDocTest {

	private static final Logger logger = LoggerFactory.getLogger(QuickStartJavaDocTest.class);
	
    private MongoDatabase db;
    
    private MongoCollection<Document> doc;
    
    private MongoClient client;
	
	
    @Before
    public void init(){
    	client = new MongoClient("192.168.225.129",27022);
    	db =client.getDatabase("test");
    	doc = 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<String, String> address1 = new HashMap<String, String>();
    	address1.put("aCode", "0000");
    	address1.put("add", "xxx000");
    	doc1.append("address", address1);
    	
    	Map<String, Object> favorites1 = new HashMap<String, Object>();
    	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<String, String> address2 = new HashMap<>();
    	address2.put("aCode", "411000");
    	address2.put("add", "個人地址2");
    	doc1.append("address", address2);
    	Map<String, Object> favorites2 = new HashMap<>();
    	favorites2.put("movies", Arrays.asList("東遊記","一路向東"));
    	favorites2.put("cites", Arrays.asList("珠海","東京"));
    	doc2.append("favorites", favorites2);
    	
    	doc.insertMany(Arrays.asList(doc1,doc2));
    	
    }
    
    @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'      $set 若是不帶$ 表示覆蓋整個數據   帶$表示覆蓋指定列
    	UpdateResult updateMany = doc.updateMany(eq("username", "lison"),new Document("$set",new Document("age",6)));
    	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<Document> ret = new ArrayList<>();
    	Block<Document> printBlock = new Block<Document>() {
			@Override
			public void apply(Document t) {
				logger.info(t.toJson());
				ret.add(t);
			}
    		
		};   	
    	//select * from users  where favorites.cites has "東莞"、"東京"
		FindIterable<Document> 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<Document> find2 = doc.find(and(regex,or));
		find2.forEach(printBlock);
		logger.info(String.valueOf(ret.size()));

    }

}
//原生java驅動 Pojo的操做方式
public class QuickStartJavaPojoTest {

	private static final Logger logger = LoggerFactory.getLogger(QuickStartJavaPojoTest.class);
	
    private MongoDatabase db;
    
    private MongoCollection<User> doc;
    
    private MongoClient client;
	
	
    @Before
    public void init(){
    	//編解ma器的list
    	List<CodecRegistry> codecResgistes = new ArrayList<>();
    	//編解ma器的list加入默認的編解ma器結合
    	codecResgistes.add(MongoClient.getDefaultCodecRegistry());
    	//生成一個pojo的編解ma器
    	CodecRegistry pojoProviders = CodecRegistries.
    			fromProviders(PojoCodecProvider.builder().automatic(true).build());
    	
    	codecResgistes.add(pojoProviders);
    	//經過編解ma器的list生成編解ma器註冊中心
    	CodecRegistry registry = CodecRegistries.fromRegistries(codecResgistes);
    	
    	//把編解ma器註冊中心放入MongoClientOptions
    	MongoClientOptions build = MongoClientOptions.builder().codecRegistry(registry).build();

    	ServerAddress serverAddress = new ServerAddress("192.168.225.129",27022);

		client = new MongoClient(serverAddress, build);

    	db =client.getDatabase("test");
    	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", "chen"));
    	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' 
    	UpdateResult updateMany = doc.updateMany(eq("username", "cang"), 
    			                  new Document("$set",new Document("age",6)));
    	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<User> ret = new ArrayList<>();
    	Block<User> printBlock = new Block<User>() {
			@Override
			public void apply(User t) {
				System.out.println(t.getUsername());
				System.out.println(t.getSalary());
				ret.add(t);
			}
    		
		};
		
    	//select * from users  where favorites.cites has "東莞"、"東京"
		FindIterable<User> 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<User> find2 = doc.find(and(regex,or));
		find2.forEach(printBlock);
		logger.info(String.valueOf(ret.size()));

    }
    
}

Spring-data-mongodb客戶端

pom文件

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.10.9.RELEASE</version>
</dependency>

Tips:
1. spring-data-mongodb的最新版本是2.x.x,若是是spring爲5.0版本以上的才推薦使用;
2. spring-data-mongodb的1.10.9版本基於spring4.3.x開發,可是默認依賴的mongodb驅動爲2.14.3,能夠將mongodb的驅動設置爲3.5.0的版本,兼容性待進一步測試;
3. spring-data-mongodb的1.10.9可能會支持3.5.0版本 mongodb驅動;
4. spring-data-mongodb通常使用pojo的方式開發;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mongo="http://www.springframework.org/schema/data/mongo"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">

	<!-- <context:property-placeholder location="classpath:/com/myapp/mongodb/config/mongo.properties" 
		/> -->
	<!-- mongodb鏈接池配置 -->
	<mongo:mongo-client host="192.168.225.129" port="27022">
		<mongo:client-options 
		      write-concern="ACKNOWLEDGED"
		      connections-per-host="100"
		      threads-allowed-to-block-for-connection-multiplier="5"
		      max-wait-time="120000"
			  connect-timeout="10000"/> 
	</mongo:mongo-client>
	
	<!-- mongodb數據庫工廠配置 -->
	<mongo:db-factory dbname="test" mongo-ref="mongo" />

    <!-- mongodb模板配置 -->
	<bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
		 <!-- <constructor-arg name="mongoConverter" ref="mappingConverter"/> -->
		<property name="writeResultChecking" value="EXCEPTION"></property>
	</bean>

</beans>
@Document(collection="users")
public class User {
	
	private ObjectId id;
		
	private String username;
	
	private String country;
	
	private Address address;
	
	private Favorites favorites;
	
	private int age;
	
	private BigDecimal salary;
	
	private float lenght;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	public Favorites getFavorites() {
		return favorites;
	}
	public void setFavorites(Favorites favorites) {
		this.favorites = favorites;
	}
	public ObjectId getId() {
		return id;
	}
	public void setId(ObjectId id) {
		this.id = id;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public BigDecimal getSalary() {
		return salary;
	}
	public void setSalary(BigDecimal salary) {
		this.salary = salary;
	}
	public float getLenght() {
		return lenght;
	}
	public void setLenght(float lenght) {
		this.lenght = lenght;
	}
	
}
//spring Pojo的操做方式
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class QuickStartSpringPojoTest {

	private static final Logger logger = LoggerFactory.getLogger(QuickStartSpringPojoTest.class);
	
	@Resource
	private MongoOperations tempelate;
    

    @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);
    	
    	tempelate.insertAll(Arrays.asList(user,user1));
    }
    
    @Test
    public void testDelete(){
    	
    	//delete from users where username = ‘lison’
    	WriteResult remove = tempelate.remove(query(where("username").is("cang ")), User.class);
    	System.out.println(remove.getN());
    	
    	//delete from users where age >8 and age <25
    	WriteResult remove2 = tempelate.remove(query(new Criteria().andOperator(where("age").gt(8),where("age").lt(25))), User.class);
    	System.out.println(remove2.getN());
    	
    }
    
    @Test
    public void testUpdate(){
    	//update  users  set age=6 where username = 'lison' 
    	WriteResult updateFirst = tempelate.updateMulti(query(where("username").is("chen")), update("age", 6), User.class);
    	System.out.println(updateFirst.getN());
    	//update users  set favorites.movies add "小電影2 ", "小電影3" where favorites.cites  has "東莞"
    	Query query = query(where("favorites.cites").is("東莞"));
		Update update = new Update().addToSet("favorites.movies").each("小電影2 ", "小電影3");
		WriteResult updateMulti = tempelate.updateMulti(query, update, User.class);
		System.out.println(updateMulti.getN());
    }
    
    @Test
    public void testFind(){
    	
    	//select * from users  where favorites.cites has "東莞"、"東京"
    	List<User> find = tempelate.find(query(where("favorites.cites").all(Arrays.asList("東莞","東京"))), User.class);
    	System.out.println(find.size());
    	
    	//select * from users  where username like '%s%' and (contry= EngLish or contry = USA)
    	String regexStr = ".*s.*";
    	//username like '%s%'
    	Criteria regex = where("username").regex(regexStr);
    	//contry= EngLish
    	Criteria or1 = where("country").is("English");
    	//contry= USA
    	Criteria or2 = where("country").is("USA");
    	
    	Criteria or = new Criteria().orOperator(or1,or2);
    	
    	Query query = query(new Criteria().andOperator(regex,or));
    	
    	List<User> find2 = tempelate.find(query, User.class);
    	
    	System.out.println(find2.size());

    }
    
}

 

開發框架版本選擇

 java 驅動與mongoDB兼容性

開發框架版本選擇

 java 驅動與jdk的兼容性

開發框架版本選擇

 spring data mongo 與java mongo驅動兼容性

mongoDB數據類型

相關文章
相關標籤/搜索