Home Database Mysql Tutorial Mongodb底层java驱动框架工具类使用

Mongodb底层java驱动框架工具类使用

Jun 07, 2016 pm 04:12 PM
java mongodb use tool Ground floor frame drive

使用MongoDB需要对文档结构进行合理的设计,以满足某些特定需求。比如随机选取文档,使用skip跳过随机个文档就没有在文档中加个随机键, 然后使用某个随机数对文档进行查询高效,随机键还能添加索引,效率更高。合理选择,合理设计。 import java.net.Unknown

使用MongoDB需要对文档结构进行合理的设计,以满足某些特定需求。比如随机选取文档,使用skip跳过随机个文档就没有在文档中加个随机键,

然后使用某个随机数对文档进行查询高效,随机键还能添加索引,效率更高。合理选择,合理设计。

import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

import com.mongodb.BasicDBList;
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;
import com.nerd.mongo.config.ConfigFactory;
/**
 * MONGOS
 * @author chenlongquan
 *
 */
public class MongoUtil {
	
	private final static ThreadLocal<Mongo> mongos = new ThreadLocal<Mongo>();
	
	public static DB getdb(){
		return getMongos().getDB(ConfigFactory.getMongoConfig().getDb());
	}
	
	public static Mongo getMongos() {
		Mongo mongo = mongos.get();
		if (mongo == null) {
			try {
				mongo = new Mongo(ConfigFactory.getMongoConfig().getIp(),ConfigFactory.getMongoConfig().getPort());
				mongos.set(mongo);
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (MongoException e) {
				e.printStackTrace();
			}
		}
		return mongo;
	}
	
	public static void close(){
		Mongo mongo = mongos.get();
		if(mongo!=null){
			mongo.close();
			mongos.remove();
		}
	}
	
	
	/**
	 * 获取集合(表)
	 * 
	 * @param collection
	 */
	public static DBCollection getCollection(String collection) {

		return getdb().getCollection(collection);
	}
......................................................
Copy after login
下面我们就可以在这上面的基础上对mongodb进行基本的crud操作

例如:

/**
	 * 插入
	 * 
	 * @param collection
	 * @param o 插入
	 *    
	 */
	public static void insert(String collection, DBObject o) {
		
		getCollection(collection).insert(o);
	}

	/**
	 * 批量插入
	 * 
	 * @param collection
	 * @param list
	 *            插入的列表
	 */
	public void insertBatch(String collection, List<DBObject> list) {

		if (list == null || list.isEmpty()) {
			return;
		}

		getCollection(collection).insert(list);

	}
Copy after login

测试用例:

insert("user1",
				new BasicDBObject().append("name", "admin3").append("type", "2").append("score", 70)
					 .append("level", 2).append("inputTime", new Date().getTime()));
Copy after login

工具类使用:

/**
	 * 删除
	 * 
	 * @param collection
	 * @param q
	 *            查询条件
	 */
	public void delete(String collection, DBObject q) {

		getCollection(collection).remove(q);
	}

	/**
	 * 批量删除
	 * 
	 * @param collection
	 * @param list
	 *            删除条件列表
	 */
	public void deleteBatch(String collection, List<DBObject> list) {

		if (list == null || list.isEmpty()) {
			return;
		}

		for (int i = 0; i < list.size(); i++) {
			getCollection(collection).remove(list.get(i));
		}
	}

	
	/**
	 * 更新
	 * 
	 * @param collection
	 * @param q
	 *            查询条件
	 * @param setFields
	 *            更新对象
	 */
	public static void update(String collection, DBObject q, DBObject setFields) {

		getCollection(collection).updateMulti(q,
				new BasicDBObject("$set", setFields));
	}

	/**
	 * 查找集合所有对象
	 * 
	 * @param collection
	 */
	public static List<DBObject> findAll(String collection) {

		return getCollection(collection).find().toArray();
	}

	/**
	 * 按顺序查找集合所有对象
	 * 
	 * @param collection
	 *            数据集
	 * @param orderBy
	 *            排序
	 */
	public static List<DBObject> findAll(String collection, DBObject orderBy) {

		return getCollection(collection).find().sort(orderBy)
				.toArray();
	}

	/**
	 * 查找(返回一个对象)
	 * 
	 * @param collection
	 * @param q
	 *            查询条件
	 */
	public static DBObject findOne(String collection, DBObject q) {

		return getCollection(collection).findOne(q);
	}

	/**
	 * 查找(返回一个对象)
	 * 
	 * @param collection
	 * @param q
	 *            查询条件
	 * @param fileds
	 *            返回字段
	 */
	public static DBObject findOne(String collection, DBObject q, DBObject fileds) {

		return getCollection(collection).findOne(q, fileds);
	}

	

	/**
	 * 分页查找集合对象,返回特定字段
	 * 
	 * @param collection
	 * @param q
	 *            查询条件
	 * @param fileds
	 *            返回字段
	 * @pageNo 第n页
	 * @perPageCount 每页记录数
	 */
	public static List<DBObject> findLess(String collection, DBObject q, DBObject fileds, int pageNo,
			int perPageCount) {

		return getCollection(collection).find(q, fileds)
				.skip((pageNo - 1) * perPageCount).limit(perPageCount)
				.toArray();
	}
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
How reliable is Binance Plaza? How reliable is Binance Plaza? May 07, 2025 pm 07:18 PM

Binance Square is a social media platform provided by Binance Exchange, aiming to provide users with a space to communicate and share information related to cryptocurrencies. This article will explore the functions, reliability and user experience of Binance Plaza in detail to help you better understand this platform.

MongoDB vs. Oracle: Exploring NoSQL and Relational Approaches MongoDB vs. Oracle: Exploring NoSQL and Relational Approaches May 07, 2025 am 12:02 AM

In different application scenarios, choosing MongoDB or Oracle depends on specific needs: 1) If you need to process a large amount of unstructured data and do not have high requirements for data consistency, choose MongoDB; 2) If you need strict data consistency and complex queries, choose Oracle.

The latest download tutorial for Ouyi OKX6.118.0 version The latest download tutorial for Ouyi OKX6.118.0 version May 07, 2025 pm 06:51 PM

The latest download tutorial for Ouyi OKX6.118.0 version: 1. Click on the quick link in the article; 2. Click on the download (if you are a web user, please register the information first). The latest Android version v6.118.0 optimizes some functions and experiences to make trading easier. Update the app now to experience a more extreme trading experience.

Composer: Installing, Updating, and Managing Dependencies Composer: Installing, Updating, and Managing Dependencies May 07, 2025 am 12:07 AM

Composer is a dependency management tool for PHP, and manages project dependencies through composer.json and composer.lock files. 1. Install Composer: Run a specific command and move composer.phar to the system path. 2. Update Composer: Use composelself-update command. 3. Dependency management: add dependencies through the composerrequire command, automatically update relevant files and download packages.

2025 Binance Binance Exchange Latest Login Portal 2025 Binance Binance Exchange Latest Login Portal May 07, 2025 pm 07:03 PM

As the world's leading cryptocurrency exchange, Binance is always committed to providing users with a safe and convenient trading experience. Over time, Binance has continuously optimized its platform features and user interface to meet the changing needs of users. In 2025, Binance launched a new login portal aimed at further improving the user experience.

2025 Binance Online Web Address 2025 Binance Online Web Address May 07, 2025 pm 06:54 PM

As the world's leading cryptocurrency exchange, Binance is always committed to providing users with a safe and convenient trading experience. Over time, Binance has continuously optimized its platform features and user interface to meet the changing needs of users. In 2025, Binance launched a new login portal aimed at further improving the user experience.

Mastering Java: Understanding Its Core Features and Capabilities Mastering Java: Understanding Its Core Features and Capabilities May 07, 2025 pm 06:49 PM

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

How to save Binance's liquidation How to save Binance's liquidation May 07, 2025 pm 07:09 PM

In cryptocurrency trading, liquidation is a common but headache. Especially when using large trading platforms like Binance, users may face the risk of losing their positions due to violent market fluctuations. This article will discuss in detail how to save Binance after the liquidation of the stock, as well as some preventive measures.

See all articles