Heim > Datenbank > MySQL-Tutorial > Hauptteil

MongoDB数据读写的几种方法

WBOY
Freigeben: 2016-06-07 15:28:33
Original
1906 Leute haben es durchsucht

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)
Nach dem Login kopieren

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

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

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

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

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

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

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

mongo SERVER:PORT/dbname --quiet script.js
Nach dem Login kopieren
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" }
Nach dem Login kopieren

任务分析:

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

}
Nach dem Login kopieren

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

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

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!