package com.zhiwei.util;

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

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;

/**
 * 文件操作mongo
 * 
 * @author admin
 *
 */
public class MongoConnection {

	private MongoClient client;

	public MongoConnection() {
		client = new MongoClient("192.168.0.11", 27217);
	}

	public MongoDatabase getdb(String dbName) {
		return client.getDatabase(dbName);
	}

	/**
	 * 更新操作，若没有则插入
	 * 
	 * @param dbName
	 * @param collection
	 * @param document
	 */
	public void insertDb(String dbName, String collection, Document document) {
		MongoDatabase db = getdb(dbName);
		MongoCollection<Document> col = db.getCollection(collection);
		Document filter = new Document();
		filter.append("name", document.get("name"));
		filter.append("type", document.get("type"));
		Document update = new Document();
		update.append("$set", new Document("url", document.get("url")));
		col.updateOne(filter, update, new UpdateOptions().upsert(true));
	}

	/**
	 * 查询
	 * 
	 * @param dbName
	 * @param collection
	 * @return
	 */
	public List<Document> find(String dbName, String collection) {
		List<Document> list = new ArrayList<>();
		MongoDatabase db = getdb(dbName);
		MongoCollection<Document> col = db.getCollection(collection);
		FindIterable<Document> fid = col.find();
		MongoCursor<Document> cur = fid.iterator();
		while (cur.hasNext()) {
			list.add(cur.next());
		}
		cur.close();
		return list;
	}

	public Document find(String dbName, String collection, Document doc) {
		MongoDatabase db = getdb(dbName);
		MongoCollection<Document> col = db.getCollection(collection);
		Document fid = col.find(doc).first();
		return fid;
	}

	/**
	 * 条件查询
	 * 
	 * @param dbName
	 * @param collection
	 * @return
	 */
	public String findOne(String dbName, String collection, String name) {
		MongoDatabase db = getdb(dbName);
		MongoCollection<Document> col = db.getCollection(collection);
		FindIterable<Document> fid = col.find(new Document().append("name", name));
		return fid.first() == null ? String.valueOf(fid.first()) : "";
	}

	public static void main(String[] args) {
		MongoConnection m = new MongoConnection();
		// for(Document doc:m.find("financePush","excelPath")) {
		// System.out.println(doc);
		// }

	}
}
