欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

分享java操作mongodb的crud代码 博客分类: mongodbnosqljava mongodbcrud增删改查 

程序员文章站 2024-02-13 14:04:52
...

代码中包括了mongodb的crud及其分页查询,排序功能

下载地址:分享java操作mongodb的crud代码

package com.zuidaima.mongodb.test;

import java.net.UnknownHostException;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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.MongoException;

public class Main {

	private Mongo mongo = null;
	private DB db = null;
	private DBCollection test;

	@Before
	public void init() {
		try {
			mongo = new Mongo("localhost");
			db = mongo.getDB("test");
			test = db.getCollection("test");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void create() {
		BasicDBObject data = new BasicDBObject().append("hosting", "hostA");
		data.put("name", "中文");
		data.put("name", "英文");
		test.save(data);
	}

	@Test
	public void load() {
		BasicDBObject query = new BasicDBObject();
		query.put("name", "中文");
		DBCursor cursor = test.find(query);
		while (cursor.hasNext()) {
			DBObject object = cursor.next();
			System.out.println(object);
		}
	}

	@Test
	public void page() {
		int count = 10;
		int page = 1;
		int skip = (page - 1) * count;
		DBCursor cursor = test.find().limit(count).skip(skip);
		while (cursor.hasNext()) {
			DBObject object = cursor.next();
			System.out.println(object);
		}
	}

	@Test
	public void sort() {
		int count = 10;
		int page = 1;
		int skip = (page - 1) * count;
		DBCursor cursor = test.find().limit(count).skip(skip)
				.sort(new BasicDBObject("_id", -1));
		while (cursor.hasNext()) {
			DBObject object = cursor.next();
			System.out.println(object);
		}
	}

	@Test
	public void update() {
		BasicDBObject query = new BasicDBObject();
		query.put("name", "中文");
		DBCursor cursor = test.find(query);
		DBObject object = cursor.next();

		BasicDBObject newObject = new BasicDBObject();
		newObject.put("name", "中文");
		newObject.put("value", "chinese");
		test.update(object, newObject);
		cursor = test.find();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	}

	@Test
	public void delete() {
		BasicDBObject query = new BasicDBObject();
		query.put("name", "中文");
		DBCursor cursor = test.find(query);
		DBObject object = cursor.next();
		test.remove(object);

		cursor = test.find();
		while (cursor.hasNext()) {
			System.out.println(cursor.next());
		}
	}

	@After
	public void destory() {
		if (mongo != null)
			mongo.close();
		mongo = null;
		db = null;
	}

}