Home Database Mysql Tutorial java操作mongodb:基本的增删改查

java操作mongodb:基本的增删改查

Jun 07, 2016 pm 03:23 PM
java mongodb Basic operate

java操作mongodb的代码,包含基本的增删改查操作 获取数据库连接工具类 package com.liuc.db;import java.net.UnknownHostException;import com.mongodb.DB;import com.mongodb.DBCollection;import com.mongodb.Mongo;/** * * @brief MongoDBUtil.java 操作

java操作mongodb的代码,包含基本的增删改查操作

获取数据库连接工具类

package com.liuc.db;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;

/**
 * 
 * @brief MongoDBUtil.java 操作mongodb工具类
 * @attention 使用注意事项
 * @author liuchao
 * @date 2013-12-30
 * @note begin modify by 修改人 修改时间  修改内容摘要说明
 */
public class MongoDBUtil {
	/**
	 * 
		* \brief 无需认证获取数据库连接
		* @return
		* @attention 方法的使用注意事项 
		* @author liuchao
		* @date 2013-12-30 
		* @note  begin modify by 修改人 修改时间   修改内容摘要说明
	 */
	public static DBCollection getDBConnectionWithoutAuth(String colName){
		try {
			Mongo mongo = new Mongo("localhost", 27017);
			DB db = mongo.getDB("liuchao");
			return db.getCollection(colName);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 
		    获取需认证获取数据库连接
		    启动登录密码认证:
			登录数据库,添加用户
			use 
			db.addUser('user1','pwd1'); 
			重启服务端开启认证服务
			mongod --auth --dbpath=D:\mongodb\db 
			接下来登录就需要用户名密码认证了
			启动客户端:
			use admin; 
			//进行登陆验证,如果不通过,是没有操作权限的了。 
			db.auth('user1','pwd1'); 
	 */
	public static DBCollection getDBConnectionWithAuth(String colName){
		try {
			Mongo mongo = new Mongo("localhost", 27017);
			DB db = mongo.getDB("liuchao");
			char[] pwd_char = "liuchao".toCharArray(); 
			boolean auth = db.authenticate("liuchao",pwd_char);//登陆验证,成功之后才能进行有效操作 
			if(!auth){ 
			    throw new RuntimeException();
			} 
			return db.getCollection(colName);
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void main(String[] args) {
		System.out.println(getDBConnectionWithAuth("users"));
		System.out.println(getDBConnectionWithoutAuth("users"));
	}
}
Copy after login
基本增删改查操作类:
package com.liuc.db;

import java.util.ArrayList;
import java.util.List;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

/**
 * 
 * @brief MognoDBCURDUtil.java 增删改查工具类
 * @attention 使用注意事项
 * @author liuchao
 * @date 2013-12-30
 * @note begin modify by 修改人 修改时间 修改内容摘要说明
 */
public class MognoDBCURDUtil {
	/**
	 * 
	 * \brief查询所有数据
	 * 
	 * @attention 方法的使用注意事项
	 * @author liuchao
	 * @date 2013-12-30
	 * @note begin modify by 修改人 修改时间 修改内容摘要说明
	 */
	private static void queryAll(String collectionName) {
		DBCollection users = MongoDBUtil
				.getDBConnectionWithAuth(collectionName);
		// db游标
		DBCursor cur = users.find();
		System.out.println("数据总条数:" + users.count());
		while (cur.hasNext()) {
			System.out.println(cur.next());
		}
	}

	/**
	 * 
	 * \brief 添加数据
	 * 
	 * @param collectionName
	 * @attention 方法的使用注意事项
	 * @author liuchao
	 * @date 2013-12-30
	 * @note begin modify by 修改人 修改时间 修改内容摘要说明 save和insert的区别
	 *       save函数实际就是根据参数条件,调用了insert或update函数.
	 *       如果想插入的数据对象存在,insert函数会报错,而save函数是改变原来的对象;
	 *       如果想插入的对象不存在,那么它们执行相同的插入操作. 这里可以用几个字来概括它们两的区别,即所谓"有则改之,无则加之".
	 */

	public static void add(String collectionName, List<DBObject> list) {

		DBCollection users = MongoDBUtil
				.getDBConnectionWithAuth(collectionName);
		users.insert(list).getN();
	}
	/**
	 * 
		* \brief 更新
		* @param collectionName
		* @param source
		* @param target
		* @attention 方法的使用注意事项 
		* @author liuchao
		* @date 2013-12-30 
		* @note  begin modify by 修改人 修改时间   修改内容摘要说明
	 */
	public static void update(String collectionName, DBObject source,
			DBObject target) {
		DBCollection users = MongoDBUtil
				.getDBConnectionWithAuth(collectionName);
		/**
		 * true,//如果数据库不存在,是否添加
        	false//多条修改
		 */
		users.update(source, target, true, false);
	}
	/**
	 * 
		* \brief 删除
		* @param collectionName
		* @param obj
		* @attention 方法的使用注意事项 
		* @author liuchao
		* @date 2013-12-30 
		* @note  begin modify by 修改人 修改时间   修改内容摘要说明
	 */
	public static void delete(String collectionName, DBObject delObj) {
		DBCollection users = MongoDBUtil
				.getDBConnectionWithAuth(collectionName);
		users.remove(delObj);
		//print("remove age >= 24: " + users.remove(new BasicDBObject("age", new BasicDBObject("$gte", 24))).getN());
	}
	/**
	 * 
		* \brief 带条件查询
		* @param collectionName
		* @param delObj
		* @attention 方法的使用注意事项 
		* @author liuchao
		* @date 2013-12-30 
		* @note  begin modify by 修改人 修改时间   修改内容摘要说明
	 */
	public static void queryWithCondition(String collectionName, DBObject condition) {
		DBCollection users = MongoDBUtil
				.getDBConnectionWithAuth(collectionName);
		//users.find(new BasicDBObject("_id", new ObjectId("4de73f7acd812d61b4626a77"))).toArray()
		users.find(condition);
	}
}
Copy after login

代码下载:http://download.csdn.net/detail/shanhuhau/6788957
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)

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Use Composer to solve the dilemma of recommendation systems: andres-montanez/recommendations-bundle Apr 18, 2025 am 11:48 AM

When developing an e-commerce website, I encountered a difficult problem: how to provide users with personalized product recommendations. Initially, I tried some simple recommendation algorithms, but the results were not ideal, and user satisfaction was also affected. In order to improve the accuracy and efficiency of the recommendation system, I decided to adopt a more professional solution. Finally, I installed andres-montanez/recommendations-bundle through Composer, which not only solved my problem, but also greatly improved the performance of the recommendation system. You can learn composer through the following address:

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

What is the CentOS MongoDB backup strategy? What is the CentOS MongoDB backup strategy? Apr 14, 2025 pm 04:51 PM

Detailed explanation of MongoDB efficient backup strategy under CentOS system This article will introduce in detail the various strategies for implementing MongoDB backup on CentOS system to ensure data security and business continuity. We will cover manual backups, timed backups, automated script backups, and backup methods in Docker container environments, and provide best practices for backup file management. Manual backup: Use the mongodump command to perform manual full backup, for example: mongodump-hlocalhost:27017-u username-p password-d database name-o/backup directory This command will export the data and metadata of the specified database to the specified backup directory.

See all articles