search
HomeDatabaseMysql TutorialMongoDB数据读写的几种方法

1、MongoDB Shell Script mongoDB的命令行使用的是类似JavaScript脚本的命令行交互,所以我们可以在shell当中使用JS的一些命令、函数等。 输入mongo命令启动mongo控制台 然后参考官方文档操作mongo数据。 常用命令有 show dbsuse db-nameshow collectionsdb.

1、MongoDB Shell Script

mongoDB的命令行使用的是类似JavaScript脚本的命令行交互,所以我们可以在shell当中使用JS的一些命令、函数等。

输入mongo命令启动mongo控制台

\

然后参考官方文档操作mongo数据。

常用命令有

show dbs
use db-name
show collections
db.collection.find()
db.collection.findOne()
db.collection.remove(args)
db.collection.insert(args)

等。CURD操作可以参考官方文档。

如果要生成大量测试数据,我们可以在mongo shell里面写一个for循环,

for (var i = 1; i <= 25; i++) db.testData.insert( { x : i } )

或者新建一个script.js将脚本放入循环内:

function insertData(dbName, colName, num) {

  var col = db.getSiblingDB(dbName).getCollection(colName);

  for (i = 0; i < num; i++) {
    col.insert({x:i});
  }

  print(col.count());

}
如何运行这个函数呢?有两种方法:

1、将其放入"~/.mongorc.js"这个文件内

2、将其保存为script.js,然后运行mongo控制台时输入如下命令,会得到后台执行:

mongo SERVER:PORT/dbname --quiet script.js
mongo控制台启动命令还有好多参数,可以参考官方文档。

2、利用MongoDB JAR包编写Java代码访问Mongo数据库

下载MongoDB Java Driver:点击打开链接

添加进Java Project内。具体API文档可以点击这里。

Small Task

下面以一个任务为例说明用法。

任务描述:定时删除三个月前的article。其中每个article与一个聚类相关联,同时数据库中还有聚类(cluster)的数据信息。每次删除article完成后,删除对应的那些无任何文章关联的聚类。

数据类型如下:

{ "_id" : ObjectId("52df7de966f0bc5d1bf4497d"), "clusterId" : 21, "docId" : 2, "title" : "test article 1", "type" : "article" }

任务分析:

1、首先需要依据条件查询到符合“三个月前的”文章数据;

2、提取所有article的id构建成一个列表;

3、提取所有涉及到的cluster的id构建成一个没有重复元素的列表;

4、删除所有满足条件的article;

5、判断每个cluster是否已经为空,若是则进行删除聚类操作。

Java代码如下:

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
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.QueryBuilder;

public class MongoMainTest {
	static int today = 0;
	static int threeMonth = 0;

    static DBObject documentFields = new BasicDBObject();
    static DBObject clusterFields = new BasicDBObject();
    static { //此处键值设为true即代表作为返回结果键值 返回
    	documentFields.put("_id", true);
    	documentFields.put("docId", true);
    	documentFields.put("clusterId", true);
    	documentFields.put("type", true);
    	
    	clusterFields.put("clusterId", true);
    	clusterFields.put("type", true);
    } // DBCursor cursor = instanceDB.find(new BasicDBObject("assign", vouch),DocumentFields);    
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Mongo m = null;
		try {
			m = new Mongo( "10.211.55.7" , 27017 );
		} catch (UnknownHostException e) {
			e.printStackTrace();
			System.exit(0);
		}
		DB db = m.getDB("clusterDb");
//		List<String> dbs = m.getDatabaseNames();
//		System.out.println(dbs);
//		DBCollection coll = db.getCollection("rkCol");
//		BasicDBObject doc = new BasicDBObject("docId",2); //此处为书写查询方法一
//		DBCursor curs = coll.find(doc);
//		DBObject obj = (DBObject)JSON.parse("{docId: 2}"); //书写查询方法二
//		curs = coll.find(obj);
//		while(curs.hasNext()) {
//			System.out.println("Cursor Count: "+curs.count());
//			System.out.println(curs.next());
//		}
		DBCollection coll = db.getCollection("rkCol");
		QueryBuilder queryBuilder = new QueryBuilder();
		DBObject articleQuery = new BasicDBObject("type", "article")//;
									.append("timestamp", new BasicDBObject("$lt", today-threeMonth))
									.append("clusterId", true); //书写查询方法三
		
		queryBuilder.and(articleQuery); //书写查询方法四
		DBCursor curs = coll.find(queryBuilder.get()); //注意方法四在实际使用时需要调用get方法生成具体query语句
		
		ArrayList<Object> articles = new ArrayList<Object>(); //此处element类型均为Object
		HashSet<Object> clusters = new HashSet<Object>();
		DBObject article = null;
		while(curs.hasNext()) {
			article = curs.next();
			articles.add(article.get("_id"));
			clusters.add(article.get("clusterId"));
		}
		
		QueryBuilder removeBuilder = new QueryBuilder();
		//注意下句使用了$in操作符,类似于{_id: articleID1} or {_id: articleID2} or {_id: articleID3} ...
		DBObject removeObject = new BasicDBObject("_id", new BasicDBObject("$in", articles));
		removeBuilder.and(removeObject);
		
		/*打印结果*/
		coll.remove(removeBuilder.get());
		DBObject articleCountQuery = null;
		for(Object o: clusters) {
			articleCountQuery = new BasicDBObject("clusterId", o);
			curs = coll.find(articleCountQuery);
			if(curs.count() != 0) {
				clusters.remove(o);
			}
		}
		removeObject = new BasicDBObject("clusterId", new BasicDBObject("$in", clusters));
		removeBuilder.and(removeObject);
		coll.remove(removeBuilder.get());
		
		
		/**
		curs = coll.find(removeBuilder.get()); 
		articles = new ArrayList<Object>();
		clusters = new HashSet<Object>();
		article = null;
		while(curs.hasNext()) {
			article = curs.next();
			articles.add(article.get("_id"));
			clusters.add(article.get("clusterId"));
		}
		/**/
		
		System.out.println(articles);
		System.out.println(clusters);
	}

}

定时操作,参考这篇博文,利用Java代码编程实现(利用开源库Quartz)。

Linux的环境可以使用crontab工具,更为简单方便。此处所需要配合使用的JS代码简略。

Statement
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
What are the differences in syntax between MySQL and other SQL dialects?What are the differences in syntax between MySQL and other SQL dialects?Apr 27, 2025 am 12:26 AM

MySQLdiffersfromotherSQLdialectsinsyntaxforLIMIT,auto-increment,stringcomparison,subqueries,andperformanceanalysis.1)MySQLusesLIMIT,whileSQLServerusesTOPandOracleusesROWNUM.2)MySQL'sAUTO_INCREMENTcontrastswithPostgreSQL'sSERIALandOracle'ssequenceandt

What is MySQL partitioning?What is MySQL partitioning?Apr 27, 2025 am 12:23 AM

MySQL partitioning improves performance and simplifies maintenance. 1) Divide large tables into small pieces by specific criteria (such as date ranges), 2) physically divide data into independent files, 3) MySQL can focus on related partitions when querying, 4) Query optimizer can skip unrelated partitions, 5) Choosing the right partition strategy and maintaining it regularly is key.

How do you grant and revoke privileges in MySQL?How do you grant and revoke privileges in MySQL?Apr 27, 2025 am 12:21 AM

How to grant and revoke permissions in MySQL? 1. Use the GRANT statement to grant permissions, such as GRANTALLPRIVILEGESONdatabase_name.TO'username'@'host'; 2. Use the REVOKE statement to revoke permissions, such as REVOKEALLPRIVILEGESONdatabase_name.FROM'username'@'host' to ensure timely communication of permission changes.

Explain the differences between InnoDB and MyISAM storage engines.Explain the differences between InnoDB and MyISAM storage engines.Apr 27, 2025 am 12:20 AM

InnoDB is suitable for applications that require transaction support and high concurrency, while MyISAM is suitable for applications that require more reads and less writes. 1.InnoDB supports transaction and bank-level locks, suitable for e-commerce and banking systems. 2.MyISAM provides fast read and indexing, suitable for blogging and content management systems.

What are the different types of JOINs in MySQL?What are the different types of JOINs in MySQL?Apr 27, 2025 am 12:13 AM

There are four main JOIN types in MySQL: INNERJOIN, LEFTJOIN, RIGHTJOIN and FULLOUTERJOIN. 1.INNERJOIN returns all rows in the two tables that meet the JOIN conditions. 2.LEFTJOIN returns all rows in the left table, even if there are no matching rows in the right table. 3. RIGHTJOIN is contrary to LEFTJOIN and returns all rows in the right table. 4.FULLOUTERJOIN returns all rows in the two tables that meet or do not meet JOIN conditions.

What are the different storage engines available in MySQL?What are the different storage engines available in MySQL?Apr 26, 2025 am 12:27 AM

MySQLoffersvariousstorageengines,eachsuitedfordifferentusecases:1)InnoDBisidealforapplicationsneedingACIDcomplianceandhighconcurrency,supportingtransactionsandforeignkeys.2)MyISAMisbestforread-heavyworkloads,lackingtransactionsupport.3)Memoryengineis

What are some common security vulnerabilities in MySQL?What are some common security vulnerabilities in MySQL?Apr 26, 2025 am 12:27 AM

Common security vulnerabilities in MySQL include SQL injection, weak passwords, improper permission configuration, and unupdated software. 1. SQL injection can be prevented by using preprocessing statements. 2. Weak passwords can be avoided by forcibly using strong password strategies. 3. Improper permission configuration can be resolved through regular review and adjustment of user permissions. 4. Unupdated software can be patched by regularly checking and updating the MySQL version.

How can you identify slow queries in MySQL?How can you identify slow queries in MySQL?Apr 26, 2025 am 12:15 AM

Identifying slow queries in MySQL can be achieved by enabling slow query logs and setting thresholds. 1. Enable slow query logs and set thresholds. 2. View and analyze slow query log files, and use tools such as mysqldumpslow or pt-query-digest for in-depth analysis. 3. Optimizing slow queries can be achieved through index optimization, query rewriting and avoiding the use of SELECT*.

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),