因为业务上的接触,其实关于nosql一直准备系统过一下,尤其是mongodb,但是因为时间问题,只能胡搞的使用。
1.安装
wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.0.6.tgz
tar -zxvf mongodb-linux-x86_64-3.0.6.tgz
2.配置环境变量
image.pngvim /etc/profile
#todo
source /etc/profile
mongo -version
3.启动
mongod &
image.png
4.使用
windows操作系统可以工具使用来链接直接看 如:
image.png
或者代码层面操作,我用的是java
<!-- maven配置 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
java配置
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import java.util.Collections;
@Configuration
@ConfigurationProperties("mongo")
@PropertySource("classpath:/mongo.properties")
public class MongoConfig {
private String mongoIp;
private Integer mongoPort;
private String operatedDb;
private String authDb;
private String userName;
private String password;
@Bean
public MongoDbFactory mongoDbLog() throws Exception {
SimpleMongoDbFactory dbName;
ServerAddress serverAddress = new ServerAddress(mongoIp, mongoPort);
if (StringUtils.isEmpty(userName)) {
dbName = new SimpleMongoDbFactory(new MongoClient(serverAddress), operatedDb);
} else {
MongoCredential mongoCredential = MongoCredential.createCredential(userName, authDb, password.toCharArray());
dbName = new SimpleMongoDbFactory(new MongoClient(serverAddress, Collections.singletonList(mongoCredential)), operatedDb);
}
return dbName;
}
@Bean
public MongoTemplate mongoTemplateLog() throws Exception {
return new MongoTemplate(mongoDbLog());
}
//get set
}
mongo.properties
mongo.mongoIp=192.168.1.110
mongo.mongoPort=27017
mongo.operatedDb=ground-transfer
mongo.authDb=admin
mongo.userName=****
mongo.password=****
注入
@Autowired
MongoTemplate mongoTemplate;
应用(还有复杂的我还没有写过,比如分页查询,各种复杂条件查询等)
mongoTemplate.insert(webhook);//插入
mongoTemplate.save(application);//类似insert,_id存在不会报错
mongoTemplate.insertAll(errList);//对象的的List插入
Criteria criteria = new Criteria();
Query query = new Query(criteria);
List<UniubiApplication> list = mongoTemplate.find(query,UniubiApplication.class);
网友评论