程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> SyBase數據庫 >> SyBase教程 >> Mongodb demo

Mongodb demo

編輯:SyBase教程

Mongodb demo


基於mongodb3.0.1, 下載mongo-java-driver-3.0.1.jar
package test.mongodb;

import java.util.HashMap;
import java.util.Map;

import org.bson.Document;
import org.bson.conversions.Bson;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class MongodbDemo {

	public static void main(String[] arsg) {
	 
		MongoClient client = new MongoClient("192.168.190.128",27017);
		//MongoClient client = new MongoClient();
	 
		MongoDatabase database  = client.getDatabase("testMongo");//Database name
	 
		//MongoCollection<> collection = database.getCollection("");
		 
        add(database);
		upate(database);
		delete(database);
		search(database);
		client.close();
	}
	
	
	
	public static void add(MongoDatabase database) {
		MongoCollection collection = database.getCollection("foo");//集合 name
		
		Map map = new HashMap();
		map.put("time", "2015-05-21 22:59");
		
		Document document = new Document("AddBy", "JAVA" ).append("append", map);
		
		collection.insertOne(document);
		
		database.createCollection("JavaCollection");
		
	}
	
	public static void delete(MongoDatabase database) {
		MongoCollection collection =  database.getCollection("foo");
		collection.deleteOne(Filters.lte("age", 22));
		
	     database.getCollection("JavaCollection").drop();
	}
	
	public static void upate(MongoDatabase database){
		MongoCollection collection = database.getCollection("foo");
		
		//collection.updateOne(Filters.gt("age",18), new Document("$set", new Document("sex","MANNN")));
		collection.updateMany(Filters.gt("age",18), new Document("$set", new Document("sex","MANNN")));
	}
	
	public static void search(MongoDatabase database){
 
		MongoCollection collection = database.getCollection("foo");
		
		Bson bsonfilter = Filters.gte("age",22);
		FindIterable find = collection.find(bsonfilter);
		
		System.out.println("collection.count():: "+ collection.count());
		
		for(Document documentT : find) {
			System.out.println(documentT.get("sex"));
		}
		 
		Document document = find.first();
		if(null !=document && document.containsKey("age")) {
	      System.out.println(document.getDouble("age"));
		}
	}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved