Table of Contents
1、MongoDB Shell Script
2、利用MongoDB JAR包编写Java代码访问Mongo数据库
Small Task
Home Database Mysql Tutorial MongoDB数据读写的几种方法

MongoDB数据读写的几种方法

Jun 07, 2016 pm 03:28 PM
mongodb several kinds data method

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)
Copy after login

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

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

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

或者新建一个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());

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

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

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

mongo SERVER:PORT/dbname --quiet script.js
Copy after login
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" }
Copy after login

任务分析:

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);
	}

}
Copy after login

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

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

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)

70B model generates 1,000 tokens in seconds, code rewriting surpasses GPT-4o, from the Cursor team, a code artifact invested by OpenAI 70B model generates 1,000 tokens in seconds, code rewriting surpasses GPT-4o, from the Cursor team, a code artifact invested by OpenAI Jun 13, 2024 pm 03:47 PM

70B model, 1000 tokens can be generated in seconds, which translates into nearly 4000 characters! The researchers fine-tuned Llama3 and introduced an acceleration algorithm. Compared with the native version, the speed is 13 times faster! Not only is it fast, its performance on code rewriting tasks even surpasses GPT-4o. This achievement comes from anysphere, the team behind the popular AI programming artifact Cursor, and OpenAI also participated in the investment. You must know that on Groq, a well-known fast inference acceleration framework, the inference speed of 70BLlama3 is only more than 300 tokens per second. With the speed of Cursor, it can be said that it achieves near-instant complete code file editing. Some people call it a good guy, if you put Curs

China Mobile: Humanity is entering the fourth industrial revolution and officially announced 'three plans” China Mobile: Humanity is entering the fourth industrial revolution and officially announced 'three plans” Jun 27, 2024 am 10:29 AM

According to news on June 26, at the opening ceremony of the 2024 World Mobile Communications Conference Shanghai (MWC Shanghai), China Mobile Chairman Yang Jie delivered a speech. He said that currently, human society is entering the fourth industrial revolution, which is dominated by information and deeply integrated with information and energy, that is, the "digital intelligence revolution", and the formation of new productive forces is accelerating. Yang Jie believes that from the "mechanization revolution" driven by steam engines, to the "electrification revolution" driven by electricity, internal combustion engines, etc., to the "information revolution" driven by computers and the Internet, each round of industrial revolution is based on "information and "Energy" is the main line, bringing productivity development

How to configure MongoDB automatic expansion on Debian How to configure MongoDB automatic expansion on Debian Apr 02, 2025 am 07:36 AM

This article introduces how to configure MongoDB on Debian system to achieve automatic expansion. The main steps include setting up the MongoDB replica set and disk space monitoring. 1. MongoDB installation First, make sure that MongoDB is installed on the Debian system. Install using the following command: sudoaptupdatesudoaptinstall-ymongodb-org 2. Configuring MongoDB replica set MongoDB replica set ensures high availability and data redundancy, which is the basis for achieving automatic capacity expansion. Start MongoDB service: sudosystemctlstartmongodsudosys

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:

How to ensure high availability of MongoDB on Debian How to ensure high availability of MongoDB on Debian Apr 02, 2025 am 07:21 AM

This article describes how to build a highly available MongoDB database on a Debian system. We will explore multiple ways to ensure data security and services continue to operate. Key strategy: ReplicaSet: ReplicaSet: Use replicasets to achieve data redundancy and automatic failover. When a master node fails, the replica set will automatically elect a new master node to ensure the continuous availability of the service. Data backup and recovery: Regularly use the mongodump command to backup the database and formulate effective recovery strategies to deal with the risk of data loss. Monitoring and Alarms: Deploy monitoring tools (such as Prometheus, Grafana) to monitor the running status of MongoDB in real time, and

Navicat's method to view MongoDB database password Navicat's method to view MongoDB database password Apr 08, 2025 pm 09:39 PM

It is impossible to view MongoDB password directly through Navicat because it is stored as hash values. How to retrieve lost passwords: 1. Reset passwords; 2. Check configuration files (may contain hash values); 3. Check codes (may hardcode passwords).

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.

Major update of Pi Coin: Pi Bank is coming! Major update of Pi Coin: Pi Bank is coming! Mar 03, 2025 pm 06:18 PM

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

See all articles