mongo的表添加字段,并赋值保存

 这个方法实现了 根据ID生成uuid 并赋值,保存到mongodb中
package org.athena.util;

import java.net.UnknownHostException;
import java.util.Map;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;

/**
 * Java + MongoDB Hello world Example
 * 
 */
public class RunUpdate {
	public static void main(String[] args) {

		try {

			@SuppressWarnings("deprecation")
			Mongo mongo = new Mongo("192.168.0.212", 27017);

			DB db = mongo.getDB("athena");
			DBCollection table = db.getCollection("ip");

			int size = (int) table.count();

			int pageSize = 20000;
			int page = 0;
			if (size % pageSize == 0) {
				page = (size / pageSize);
			} else {
				page = (size / pageSize) + 1;
			}
			for (int i = 1; i < page; i++) {
				int a = (i - 1) * pageSize;
				int b = i * pageSize;
				DBCursor cursor = table.find().skip(a).limit(b);// PAGESIZE=20000
				String Path1st = null;
				String Path2nd = null;
				String Path3rd = null;
				String Path4th = null;
				while (cursor.hasNext()) {
					@SuppressWarnings("unchecked")
					Map map = cursor.next().toMap();
					String oid = map.get("_id").toString();
					Path1st = oid.substring(0, 4);
					Path2nd = oid.substring(4, 8);
					Path3rd = oid.substring(8, 12);
					Path4th = oid.substring(12, oid.length());
					String uuid = Path1st + "-" + Path2nd + "-" + Path3rd + "-"+ Path4th;
					map.put("uuid", uuid);
//					map.remove("uuid");
					table.update(new BasicDBObject("_id", new ObjectId(oid)),new BasicDBObject(map));
				}
			}
			System.out.println("Done");

		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
}
    

你可能感兴趣的:(mongo)