Mongodb安装与spring中基本使用
本文所介绍环境为win7环境下运行, 从官网中(https://www.mongodb.com/download-center?jmp=nav#production)下载windows安装版msi文件,完成安装,
1、进入安装目录,在与bin目录的同级的目录中创建data文件夹,再在data目录中分别创建log,db目录,进入bin目录创建文件mongod.cfg,内容如下
mongod.cfg(注意:空格请不要有tab)
systemLog:
destination: file
path: ..\data\log\mongod.log
logAppend: true
storage:
dbPath: ..\data\db
net:
bindIp: 127.0.0.1
port: 27018
配置文件指定了数据文件位置及日志位置
2、命令行进入bin路径下,执行下面命令启动mongodb
mongod --config "mongod.cfg"
3、打开新命令行窗口,进入bin路径下,使用mongo客户端完成一些简单的操作(为了更直观观察结果可以使用robomongo可视化工具)
客户端连接到mongodb
mongo --host 127.0.0.1 --port 27018
切换/创建数据库(创建hell数据库)
use hell
查询所有数据库
show dbs;
删除数据库(需切换到当前数据库下)
db.dropDatabase();
查看当前db状态
db.stats()
查看当前db的链接机器地址
db.getMongo()
创建集合(table)
db.createCollection("user");
查看集合(table)
show collections
往user集合添加数据
db.user.insert({"name":"mixfate","age":1});
查找集合user中的数据
db.user.find();
删除集合user中的数据(其中{}条件表示不作限制)
db.user.remove({});
下面新建一个spring项目完成对mongodb的简单操作
4、新建pom.xml
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hode</groupId>
<artifactId>spring-mongodb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<spring.version>4.3.2.RELEASE</spring.version>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<mongodb.version>1.9.0.RELEASE</mongodb.version>
<slf4j.version>1.7.12</slf4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${mongodb.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
5、新建配置文件 applicationContext.xml,log4j.properties,内容分别如下
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="127.0.0.1"/>
<property name="port" value="27018"/>
</bean>
<bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
<constructor-arg name="mongo" ref="mongo"/>
<constructor-arg name="databaseName" value="hell"/>
</bean>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
</bean>
</beans>
log4j.properties
log4j.rootLogger=INFO,Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-4r %d{yyyy-MM-dd HH:mm:ss,SSS} [%t] %-5p %c %x - %m%n
log4j.logger.com.hode=DEBUG
6、新建一个user类,以及创建一个测试类
User.java
package com.hode.model;
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MongoDBTest.java
package com.hode;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.hode.model.User;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MongoDBTest {
private Logger log = Logger.getLogger(getClass());
@Autowired
MongoTemplate template;
@Test
public void init(){
template.insert("{name:\"mixfate\",level:1000}","user");
}
@Test
public void testFind(){
log.info(template);
//{}里面不含任何条件,表示查询所有
List<User> result = template.find(new BasicQuery("{}"), User.class);
for(User u:result){
log.info(u.getName());
}
log.info(result.size());
log.info("test is ok");
}
@Test
public void testInsert(){
//插入json数据name为:hode+当前时间 or 当前时间+hode
template.insert("{name:\"hode"+new Date()+"\"}", "user");
template.insert("{name:\""+new Date()+"hode\"}", "user");
}
@Test
public void testRemove(){
//删除所有name以hode开头的数据
CriteriaDefinition cd = new Criteria("name").regex("^hode.*");
template.remove(Query.query(cd), "user");
//删除所有name以hode结尾的数据
cd = new Criteria("name").regex(".*hode$");
template.remove(Query.query(cd), "user");
}
@Test
public void testUpdate(){
//将init初始数据的level改为10000
Update update = new Update().set("level", 10000);
template.updateFirst(new BasicQuery("{name:\"mixfate\",level:1000}"), update, "user");
}
}
结束。