1:安装mongodb
(1):下载mongodb,解压,在安装目录中创建data目录(与bin目录同级),在data目录下创建db目录
(2):启动mongodb。进入cmd命令行工具,进入mongodb安装目录下的bin目录,输入命令 mongod -dbpath '{HOME}/data/db'
(3):打开浏览器,输入:http://localhost:27017,显示:It looks like you are trying to access MongoDB over HTTP on the native driver port.说明启动成功。
2:使用eclipse创建一个maven项目开操作mongodb数据库。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/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.chu</groupId>
- <artifactId>mongotest</artifactId>
- <packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <name>mongotest Maven Webapp</name>
- <url>http://maven.apache.org</url>
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>3.8.1</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mongodb</groupId>
- <artifactId>mongo-java-driver</artifactId>
- <version>2.10.1</version>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-core-asl</artifactId>
- <version>1.9.9</version>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.9</version>
- </dependency>
- </dependencies>
- <build>
- <finalName>mongotest</finalName>
- </build>
- </project>
java代码如下:
- package com.mongo.action;
- import java.net.UnknownHostException;
- import java.util.List;
- import com.mongo.po.User;
- import com.mongo.service.UserService;
- public class UserAction {
- private UserService userService = new UserService();
- public void save() throws UnknownHostException{
- User user = new User();
- user.setId(1);
- user.setName("jinhui");
- user.setAddress("beijing");
- this.userService.save(user);
- }
- public void update()throws UnknownHostException{
- User user = new User();
- user.setId(1);
- user.setName("manman");
- user.setAddress("hebei");
- this.userService.update(user);
- }
- public List<User> findAll()throws UnknownHostException{
- return this.userService.findAll();
- }
- public void remove()throws UnknownHostException{
- this.userService.remove(1);
- }
- public static void main(String[] args)throws UnknownHostException {
- UserAction userAction = new UserAction();
- userAction.save();
- // userAction.update();
- // userAction.remove();
- List<User> list = userAction.findAll();
- for(User user : list){
- System.out.println(user);
- }
- }
- }
- package com.mongo.service;
- import java.net.UnknownHostException;
- import java.util.List;
- import com.mongo.dao.UserDao;
- import com.mongo.po.User;
- public class UserService {
- private UserDao userDao = new UserDao();
- /**
- * 保存
- * @param user
- * @throws UnknownHostException
- */
- public void save(User user) throws UnknownHostException{
- this.userDao.save(user);
- }
- /**
- * 更新
- * @param user
- * @throws UnknownHostException
- */
- public void update(User user) throws UnknownHostException {
- this.userDao.update(user);
- }
- /**
- * 查询所有
- * @return
- * @throws UnknownHostException
- */
- public List<User> findAll() throws UnknownHostException{
- return this.userDao.findAll();
- }
- /**
- * 删除操作
- * @param id
- * @throws UnknownHostException
- */
- public void remove(int id) throws UnknownHostException{
- this.userDao.remove(id);
- }
- }
- package com.mongo.dao;
- import java.net.UnknownHostException;
- import java.util.ArrayList;
- import java.util.List;
- import com.mongo.po.User;
- import com.mongodb.BasicDBObject;
- import com.mongodb.DB;
- import com.mongodb.DBCollection;
- import com.mongodb.DBCursor;
- import com.mongodb.DBObject;
- import com.mongodb.Mongo;
- import com.mongodb.util.JSON;
- public class UserDao {
- /**
- * 保存
- * @param user
- * @throws UnknownHostException
- */
- public void save(User user) throws UnknownHostException {
- Mongo mongo = new Mongo();
- DB myMongo = mongo.getDB("myMongo");
- DBCollection userCollection = myMongo.getCollection("user");
- DBObject dbo = (DBObject) JSON.parse(user.toJson());
- userCollection.insert(dbo);
- }
- /**
- * 更新
- * @param user
- * @throws UnknownHostException
- */
- public void update(User user) throws UnknownHostException {
- Mongo mongo = new Mongo();
- DB myMongo = mongo.getDB("myMongo");
- DBCollection userCollection = myMongo.getCollection("user");
- BasicDBObject baseDBO = new BasicDBObject();
- baseDBO.put("id", user.getId());
- DBObject newDBO = (DBObject) JSON.parse(user.toJson());
- userCollection.update(baseDBO, newDBO);
- }
- /**
- * 查询所有
- * @return
- * @throws UnknownHostException
- */
- public List<User> findAll() throws UnknownHostException{
- Mongo mongo = new Mongo();
- DB myMongo = mongo.getDB("myMongo");
- DBCollection userCollection = myMongo.getCollection("user");
- DBCursor cursor=userCollection.find();
- List<User> userList = new ArrayList<User>();
- while(cursor.hasNext()){
- User user = new User();
- user.parse(cursor.next());
- userList.add(user);
- }
- return userList;
- }
- /**
- * 删除操作
- * @param id
- * @throws UnknownHostException
- */
- public void remove(int id) throws UnknownHostException{
- Mongo mongo = new Mongo();
- DB myMongo = mongo.getDB("myMongo");
- DBCollection userCollection = myMongo.getCollection("user");
- BasicDBObject baseDBO =new BasicDBObject();
- baseDBO.put("id", id);
- //删除某一条记录
- userCollection.remove(baseDBO);
- }
- }
- package com.mongo.po;
- import com.mongo.utils.JsonUtils;
- import com.mongodb.DBObject;
- public class User {
- private int id;
- private String name;
- private String address;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getAddress() {
- return address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- public String toJson(){
- return JsonUtils.toJson(this);
- }
- public void parse(DBObject dbo){
- this.setId((Integer)dbo.get("id"));
- this.setName((String)dbo.get("name"));
- this.setAddress((String)dbo.get("address"));
- }
- public String toString(){
- return "id:"+id+",name:"+name+",address:"+address;
- }
- }
- package com.mongo.utils;
- import java.io.OutputStream;
- import org.codehaus.jackson.map.ObjectMapper;
- import org.codehaus.jackson.type.TypeReference;
- /**
- * Json转化工具,可以实现java对象和json字符串之间的互相转化<br />
- *
- */
- public class JsonUtils {
- static ObjectMapper objectMapper = new ObjectMapper();
- /**
- * java 对象转换为json 存入流中
- *
- * @param obj
- * @param out
- */
- public static String toJson(Object obj) {
- String s = "";
- try {
- s = objectMapper.writeValueAsString(obj);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return s;
- }
- /**
- * java 对象转换为json 存入流中
- *
- * @param obj
- * @param out
- */
- public static void toJson(Object obj, OutputStream out) {
- try {
- objectMapper.writeValue(out, obj);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * json 转为java对象
- *
- * @param json
- * @param obj
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static void fromJson(String json, Object obj, Class valueType) {
- try {
- obj = objectMapper.readValue(json, valueType);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * json 转为java对象
- * @param json
- * @param obj
- * @param valueTypeRef
- */
- @SuppressWarnings("rawtypes")
- public static void fromJson(String json, Object obj, TypeReference valueTypeRef) {
- try {
- obj = objectMapper.readValue(json, valueTypeRef);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * json 转为java对象
- *
- * @param json
- * @param obj
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static Object fromJson(String json, Class valueType) {
- Object obj = null;
- try {
- obj = objectMapper.readValue(json, valueType);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return obj;
- }
- /**
- * json 转为java对象
- *
- * @param json
- * @param obj
- * @param valueTypeRef
- */
- @SuppressWarnings({ "rawtypes", "hiding" })
- public static <Object> Object fromJson(String json, TypeReference valueTypeRef) {
- Object obj = null;
- try {
- obj = objectMapper.readValue(json, valueTypeRef);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return obj;
- }
- }
3:使用客户端工具查看数据: