List of usage examples for com.mongodb DBCollection insert
public WriteResult insert(final List<? extends DBObject> documents)
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
License:Apache License
/** * Mongo ID generation like it is done in the grails gorm framework * * @param collectionName//from w w w .ja v a 2s .c om * The name of the collection the id should be generated for * @param db * The mongodb connection * @return a new id */ private Long generateIdentifier(String collectionName, DB db) { // get or create the Collection for the ID storage DBCollection dbCollection = db.getCollection(collectionName + ".next_id"); // create entry to store the newly generated id DBObject nativeEntry = new BasicDBObject(); while (true) { DBCursor result = dbCollection.find().sort(new BasicDBObject("_id", -1)).limit(1); long nextId; if (result.hasNext()) { final Long current = (Long) result.next().get("_id"); nextId = current + 1; } else { nextId = 1; } nativeEntry.put("_id", nextId); final WriteResult writeResult = dbCollection.insert(nativeEntry); final CommandResult lastError = writeResult.getLastError(); if (lastError.ok()) { break; } final Object code = lastError.get("code"); // duplicate key error try again if (code != null && code.equals(11000)) { continue; } break; } return (Long) nativeEntry.get("_id"); }
From source file:com.ff.reportgenerator.mongodb.DynamicDatabaseWS.java
public void updateDatabase(ArrayList projects, DelegateWS dg) throws Exception { DB myDB = getDB(DB_NAME);/*w w w . ja v a 2s . com*/ myDB.dropDatabase(); // clear old records myDB = getDB(DB_NAME); DBCollection coll = myDB.getCollection("projects"); int total = projects.size(); //System.out.println(total+" records!"); Iterator it = projects.iterator(); int count = 0; while (it.hasNext()) { String json = (String) it.next(); if (json != null) { DBObject dbObject = (DBObject) JSON.parse(json); coll.insert(dbObject); count++; } else { System.out.println("NULL RECORD!"); } //count++; dg.sendUpdate(Utility.percentage(count, total) + ""); } }
From source file:com.foodtruckdata.mongodb.UsersInput.java
@Override public String AddTruck(String title, String logo_img, String menu_img, String phone, String email, String password) {/*from w w w . j a v a2 s.c o m*/ BasicDBObject document = new BasicDBObject(); document.put("title", title); document.put("phone", phone); document.put("email", email); document.put("Schedules", (new Object[] {})); document.put("Followers", (new Object[] {})); document.put("Ratings", (new Object[] {})); document.put("password", password); DBCollection coll = mongoDB.getCollection("Trucks"); coll.insert(document); ObjectId truck_id = (ObjectId) document.get("_id"); if (logo_img != null && logo_img != "") { this.storeFile(logo_img, title, truck_id); } if (menu_img != null && menu_img != "") { this.storeFile(menu_img, title, truck_id); } return truck_id.toString(); }
From source file:com.foodtruckdata.mongodb.UsersInput.java
@Override public String AddUser(String firstName, String lastName, String email, Double lat_h, Double lng_h, Double lat_w, Double lng_w) {//from ww w . ja va 2s . c om BasicDBObject document = new BasicDBObject(); document.put("FirstName", firstName); document.put("LastName", lastName); document.put("Email", email); document.put("Latitude_home", lat_h); document.put("Longitude_home", lng_h); document.put("Latitude_work", lat_w); document.put("Longitude_work", lng_w); DBCollection coll = mongoDB.getCollection("Users"); coll.insert(document); ObjectId user_id = (ObjectId) document.get("_id"); return user_id.toString(); }
From source file:com.fuction.MongoDB.java
public static void input(ArrayList<String> lsResult) { try {//from ww w. j a va2s . co m Mongo mongo = new Mongo(HOST, PORT); DB db = mongo.getDB(DB); DBCollection collection = db.getCollection("Data"); for (String s : lsResult) { DBObject dbObject = (DBObject) JSON.parse(s); collection.insert(dbObject); } } catch (Exception e) { System.err.println(e.getClass().getName() + ": " + e.getMessage()); } }
From source file:com.gdn.x.ui.function.Permute.java
static void permute(java.util.List<Integer> arr, int k) { for (int i = k; i < arr.size(); i++) { java.util.Collections.swap(arr, i, k); permute(arr, k + 1);//from ww w . ja v a2s .c o m java.util.Collections.swap(arr, k, i); } if (k == arr.size() - 1) { MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("tool_data"); DBCollection coll = db.getCollection("combination"); BasicDBObject doc = new BasicDBObject(); doc.put("weight", java.util.Arrays.toString(arr.toArray())); coll.insert(doc); System.out.println(java.util.Arrays.toString(arr.toArray())); } }
From source file:com.github.nlloyd.hornofmongo.adaptor.Mongo.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) @JSFunction// w w w. j ava 2 s .c o m public void insert(final String ns, Object obj, int options) { Object rawObj = BSONizer.convertJStoBSON(obj, true); DBObject bsonObj = null; if (rawObj instanceof DBObject) bsonObj = (DBObject) rawObj; try { int dbSeparatorIdx = ns.indexOf('.'); com.mongodb.DB db = innerMongo.getDB(ns.substring(0, dbSeparatorIdx)); String collectionName = ns.substring(dbSeparatorIdx + 1); DBCollection collection = db.getCollection(collectionName); collection.setDBEncoderFactory(HornOfMongoBSONEncoder.FACTORY); collection.setDBDecoderFactory(HornOfMongoBSONDecoder.FACTORY); // unfortunately the Java driver does not expose the _allow_dot // argument in insert calls so we need to translate system.indexes // inserts into index creation calls through the java driver if (collectionName.endsWith("system.indexes")) { db.getCollection("system.indexes").insert(Arrays.asList(bsonObj)); } else { int oldOptions = collection.getOptions(); collection.setOptions(options); List insertObj = null; if (rawObj instanceof List) insertObj = (List) rawObj; else insertObj = Arrays.asList(rawObj); collection.insert(insertObj); collection.setOptions(oldOptions); } saveLastCalledDB(db); } catch (MongoException me) { handleMongoException(me); } }
From source file:com.glaf.wechat.mongodb.service.impl.WxMongoDBLogServiceImpl.java
License:Apache License
public void save(WxLog bean) { bean.setId(Long.MAX_VALUE - System.currentTimeMillis()); bean.setCreateTime(new Date()); bean.setSuffix("_" + DateUtils.getNowYearMonthDay()); try {/*w ww.ja v a 2s .com*/ wxLogs.put(bean); } catch (InterruptedException ex) { } /** * ??1? */ if (wxLogs.size() >= conf.getInt("wx_log_step", 100) || ((System.currentTimeMillis() - lastUpdate) / 60000 > 0)) { DB db = mongoTemplate.getDb(); WxLog model = null; while (!wxLogs.isEmpty()) { model = wxLogs.poll(); String tableName = "wx_log" + model.getSuffix(); DBCollection coll = db.getCollection(tableName); if (coll != null) { BasicDBObject row = new BasicDBObject(); row.put("id", model.getId()); row.put("accountId", model.getAccountId()); row.put("actorId", model.getActorId()); row.put("openId", model.getOpenId()); row.put("flag", Integer.valueOf(model.getFlag())); row.put("ip", model.getIp()); row.put("operate", model.getOperate()); row.put("content", model.getContent()); row.put("createTime", model.getCreateTime().getTime()); coll.insert(row); logger.debug("insert row:" + model.getId()); } } lastUpdate = System.currentTimeMillis(); logger.debug("submit ok."); } }
From source file:com.glaf.wechat.mongodb.service.impl.WxMongoDBLogServiceImpl.java
License:Apache License
public void saveAll() { /**/* ww w . ja va 2 s.co m*/ * ??1? */ if (wxLogs.size() >= conf.getInt("wx_log_step", 100) || ((System.currentTimeMillis() - lastUpdate) / 60000 > 0)) { DB db = mongoTemplate.getDb(); WxLog model = null; while (!wxLogs.isEmpty()) { model = wxLogs.poll(); String tableName = "wx_log" + model.getSuffix(); DBCollection coll = db.getCollection(tableName); if (coll != null) { BasicDBObject row = new BasicDBObject(); row.put("id", model.getId()); row.put("accountId", model.getAccountId()); row.put("actorId", model.getActorId()); row.put("openId", model.getOpenId()); row.put("flag", Integer.valueOf(model.getFlag())); row.put("ip", model.getIp()); row.put("operate", model.getOperate()); row.put("content", model.getContent()); row.put("createTime", model.getCreateTime().getTime()); coll.insert(row); logger.debug("insert row:" + model.getId()); } } lastUpdate = System.currentTimeMillis(); logger.debug("submit ok."); } }
From source file:com.google.api.services.samples.analytics.cmdline.CoreReportingApiReferenceSample.java
License:Apache License
/** * Prints all the rows of data returned by the API. * @param gaData the data returned from the API. * @param collection/* ww w. j a v a 2 s .c o m*/ * @param d */ private static void insertVisitedCompaniesData(GaData gaData, DBCollection collection, Date d) throws JSONException { if (gaData.getTotalResults() > 0) { System.out.println("Data Table: " + collection); for (List<String> rowValues : gaData.getRows()) { Map jsonMap = (Map) JSON.parse(rowValues.get(0)); if (jsonMap.get("demandbase_sid") == null) { continue; } DBObject dbObject = new BasicDBObject(jsonMap); dbObject.removeField("ip"); HashMap<Object, Object> map = new HashMap<Object, Object>(); map.put("demandbase_sid", dbObject.get("demandbase_sid")); BasicDBObject objectToRemove = new BasicDBObject(map); DBObject andRemove = collection.findAndRemove(objectToRemove); if (andRemove == null) { dbObject.put("firstVisitDate", new SimpleDateFormat("yyyy/MM/dd").format(d)); } else { dbObject.put("firstVisitDate", andRemove.get("firstVisitDate")); } collection.insert(dbObject); } } else { System.out.println("No data"); } }