List of usage examples for com.mongodb DBCollection insert
public WriteResult insert(final List<? extends DBObject> documents)
From source file:edu.stanford.epad.common.util.MongoDBOperations.java
License:Open Source License
/** * Saves a json doc to mongoDB/* w ww.j a v a 2 s .c om*/ * @param jsonString * @param collection * @throws Exception */ public static void saveJsonToMongo(String jsonString, String collection) throws Exception { try { DB db = MongoDBOperations.getMongoDB(); if (db == null) { log.warning("No connection to Mongo DB"); return; } DBCollection coll = db.getCollection(collection); DBObject dbObject = (DBObject) JSON.parse(jsonString); //TODO: Check if document exists and replace instead of insert coll.insert(dbObject); } catch (Exception e) { log.warning("Error saving to mongodb:", e); throw e; } }
From source file:edu.stanford.epad.common.util.MongoDBOperations.java
License:Open Source License
/** * Converts and saves an annotation to mongoDB * @param annotationID//from w ww .ja v a 2s . co m * @param aimXML * @param collection * @throws Exception */ public static void saveAnnotationToMongo(String annotationID, String aimXML, String collection) throws Exception { try { DB db = MongoDBOperations.getMongoDB(); if (db == null) { log.warning("No connection to Mongo DB"); return; } if (aimXML == null || aimXML.trim().length() == 0) return; String jsonString = XML.toJSONObject(aimXML).toString(0); ; if (jsonString == null) throw new Exception("Error converting to json"); DBCollection dbColl = db.getCollection(collection); BasicDBObject dbObj = new BasicDBObject("ImageAnnotationCollection.uniqueIdentifier.root", 1); dbColl.createIndex(dbObj, "uid_idx", true); // Does not create index, if it already exists BasicDBObject query = new BasicDBObject(); query.put("ImageAnnotationCollection.uniqueIdentifier.root", annotationID); DBObject dbObject = (DBObject) JSON.parse(jsonString); DBCursor cursor = dbColl.find(query); if (cursor.count() > 0) { log.info("Updating existing annotation in mongoDB:" + annotationID + " in " + collection); dbColl.update(query, dbObject, true, false); } else { log.info("Creating new annotation in mongoDB:" + annotationID + " in " + collection); dbColl.insert(dbObject); } } catch (Exception e) { log.warning("Error saving AIM to mongodb:", e); throw e; } }
From source file:edu.umass.cs.gnsserver.database.MongoRecords.java
License:Apache License
@Override public void insert(String collectionName, String guid, JSONObject value) throws FailedDBOperationException, RecordExistsException { db.requestStart();//ww w. j a v a2 s .c o m try { db.requestEnsureConnection(); DBCollection collection = db.getCollection(collectionName); DBObject dbObject; try { dbObject = (DBObject) JSON.parse(value.toString()); } catch (Exception e) { throw new FailedDBOperationException(collectionName, guid, "Unable to parse json" + e.getMessage()); } try { collection.insert(dbObject); } catch (DuplicateKeyException e) { throw new RecordExistsException(collectionName, guid); } catch (MongoException e) { DatabaseConfig.getLogger().log(Level.FINE, "{0} insert failed: {1}", new Object[] { dbName, e.getMessage() }); throw new FailedDBOperationException(collectionName, dbObject.toString(), "Original mongo exception:" + e.getMessage()); } } finally { db.requestDone(); } }
From source file:edu.wayne.cs.fms.controller.CRUD.java
public static void Insert(FlightInfo info, MongoClient mongoClient) { //MongoClient mongoClient = Connector.connect("localhost", 27017); DB db = mongoClient.getDB("project"); DBCollection flight = db.getCollection("flight"); BasicDBObject query = new BasicDBObject("FL_DATE", info.getDate()).append("UNIQUE_CARRIER", info.getCarrier());/*from ww w .j ava2s.c o m*/ query.append("FL_NUM", info.getTailNum()).append("ORIGIN_CITY_NAME", info.getDepCity()); query.append("DEST_CITY_NAME", info.getArrCity()).append("CRS_DEP_TIME", info.getCrsDepTime()); query.append("CRS_ARR_TIME", info.getCrsArrTime()).append("DISTANCE", info.getDistance()); query.append("CANCELLED", info.getCancel()); if (info.getCancel() == 0) { query.append("DEP_TIME", info.getDepTime()).append("DEP_DELAY", info.getDepDelay()); query.append("ARR_TIME", info.getArrTime()).append("ARR_DELAY", info.getArrDelay()); } System.out.println(query); flight.insert(query); //mongoClient.close(); }
From source file:es.devcircus.mongodb_examples.hello_world.Main.java
License:Open Source License
/** * Mtodo que inserta un nuevo documento en la base de datos. *///w w w. jav a 2 s . c o m public static void insertIngADocument() { System.out.println(); System.out.println("---------------------------------------------------------------"); System.out.println(" Inserting a Document "); System.out.println("---------------------------------------------------------------"); System.out.println(); /* Inserting a Document * * Once you have the collection object, you can insert documents into * the collection. For example, lets make a little document that in * JSON would be represented as*/ /*{ "name" : "MongoDB", "type" : "database", "count" : 1, "info" : { x : 203, y : 102 } }*/ /*Notice that the above has an "inner" document embedded within it. * To do this, we can use the BasicDBObject class to create the * document (including the inner document), and then just simply * insert it into the collection using the insert() method.*/ System.out.print(" Insertando elemento ..."); DBCollection coll = db.getCollection(TEST_COLLECTION); BasicDBObject doc = new BasicDBObject(); doc.put("name", "MongoDB"); doc.put("type", "database"); doc.put("count", 1); BasicDBObject info = new BasicDBObject(); info.put("x", 203); info.put("y", 102); doc.put("info", info); coll.insert(doc); System.out.println("[OK]\n"); }
From source file:es.devcircus.mongodb_examples.hello_world.Main.java
License:Open Source License
/** * Mtodo que aade mltiples documentos a nuestra coleccin dentro de la * base de datos.//from w w w. j a v a2 s . co m */ public static void addingMultipleDocuments() { System.out.println(); System.out.println("---------------------------------------------------------------"); System.out.println(" Adding Multiple Documents "); System.out.println("---------------------------------------------------------------"); System.out.println(); /*Adding Multiple Documents In order to do more interesting things with queries, let's add multiple * simple documents to the collection. These documents will just be*/ /*{ "i" : value }*/ /*and we can do this fairly efficiently in a loop*/ System.out.print(" Insertando elementos ..."); DBCollection coll = db.getCollection(TEST_COLLECTION); for (int i = 0; i < 10; i++) { coll.insert(new BasicDBObject().append("i", i)); } System.out.println("[OK]"); /*Notice that we can insert documents of different "shapes" into the * same collection. This aspect is what we mean when we say that * MongoDB is "schema-free"*/ }
From source file:es.upv.dsic.elp.iJulienne.MongoDB.java
License:Open Source License
public static void saveData(String maudeInput, String maudeOutput) { MongoClient mongo;//from w ww . j a va 2s . c o m DB db; //WARNING: Configure with your own data try { mongo = new MongoClient("YOUR_SERVER_ADDRESS", YOUR_SERVER_PORT); } catch (UnknownHostException e) { return; } db = mongo.getDB("ijulienne"); //WARNING: Configure with your own data boolean auth = db.authenticate("YOUR_USER", "YOUR_PASSWORD".toCharArray()); if (auth) { DBCollection table = db.getCollection("ijulienne"); BasicDBObject document = new BasicDBObject(); document.put("input", maudeInput); document.put("output", maudeOutput); table.insert(document); } mongo.close(); }
From source file:eu.artist.cloud.auditors.AbstractedAvailabilityLogger.java
License:Open Source License
/** * @param args/*w ww .j a va 2s . c o m*/ */ public void logAvailability(ArrayList<String> TemplateIDs, String DBuser, String DBpass, String databaseIP) throws UnknownHostException, MongoException { // TODO Auto-generated method stub //needs to be periodic - but periodicity may be on the previous level-> Availability Auditor //better on the Availability Auditor level, since it will have refreshed also the state //needs to raise one thread per node, concurrent requests for all nodes? //sla is per template id? logically yes, so thread must be per template id //mongodb connection //we need to pass an object that will be the DB record and will contain all necessary information //this object will be transformed to json //more efficient to pass an arraylist of these objects (for all template IDs in one sample) and make once //the connection to the DB (for needed in the basic operation) for (String record : TemplateIDs) { Mongo mongoClient = new Mongo(databaseIP); DB db = mongoClient.getDB("3alib"); System.out.println("Host address for Backend DB:" + databaseIP); Set<String> colls = db.getCollectionNames(); for (String s : colls) { System.out.println("These are the collections... " + s); } DBCollection coll = db.getCollection("log_samples"); //log sample /*BasicDBObject doc = new BasicDBObject("name1", "MongoDB2"). append("type", "database"). append("count", 1). append("info", new BasicDBObject("x", 203).append("y", 102)); */ //DBObject obj=new DBObject(); JSON jsonObj = new JSON(); DBObject obj = (DBObject) jsonObj.parse(record); //BasicDBObject doc=new BasicDBObject(record); ObjectId obid = new ObjectId(); //System.out.println("This is the id:"+obj.get("_id")); coll.insert(obj); DBObject myDoc = coll.findOne(); //System.out.println(myDoc); //coll. mongoClient.close(); //log file must be per template ID so that it can be appended each time, if we start stop the auditing action //ideally templateID_month_year //return 0; } System.out.println("Records included"); }
From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java
License:EUPL
/** * Inserts an object into the specified collection. * @param obj - object to be inserted in the collection * @param collection - collection where the object is inserted * @return the id associated to the object in the collection *//*from w ww . j av a 2 s . c o m*/ public String insert(final DBObject obj, final String collection) { checkArgument(obj != null, "Uninitialized object"); checkArgument(isNotBlank(collection), "Uninitialized or invalid collection"); final DB db = client().getDB(CONFIG_MANAGER.getDbName()); final DBCollection dbcol = db.getCollection(collection); try { dbcol.insert(obj); } catch (DuplicateKeyException dke) { throw new MongoDBDuplicateKeyException(dke.getMessage()); } return ObjectId.class.cast(obj.get("_id")).toString(); }
From source file:example.AggregationExample.java
License:Apache License
/** * Run this main method to see the output of this quick example. * * @param args takes no args//from www . j a v a 2 s . c o m * @throws UnknownHostException if it cannot connect to a MongoDB instance at localhost:27017 */ public static void main(final String[] args) throws UnknownHostException { // connect to the local database server MongoClient mongoClient = new MongoClient(); // get handle to "mydb" DB db = mongoClient.getDB("mydb"); // Authenticate - optional // boolean auth = db.authenticate("foo", "bar"); // Add some sample data DBCollection coll = db.getCollection("aggregationExample"); coll.insert(new BasicDBObjectBuilder().add("employee", 1).add("department", "Sales").add("amount", 71) .add("type", "airfare").get()); coll.insert(new BasicDBObjectBuilder().add("employee", 2).add("department", "Engineering").add("amount", 15) .add("type", "airfare").get()); coll.insert(new BasicDBObjectBuilder().add("employee", 4).add("department", "Human Resources") .add("amount", 5).add("type", "airfare").get()); coll.insert(new BasicDBObjectBuilder().add("employee", 42).add("department", "Sales").add("amount", 77) .add("type", "airfare").get()); // create our pipeline operations, first with the $match DBObject match = new BasicDBObject("$match", new BasicDBObject("type", "airfare")); // build the $projection operation DBObject fields = new BasicDBObject("department", 1); fields.put("amount", 1); fields.put("_id", 0); DBObject project = new BasicDBObject("$project", fields); // Now the $group operation DBObject groupFields = new BasicDBObject("_id", "$department"); groupFields.put("average", new BasicDBObject("$avg", "$amount")); DBObject group = new BasicDBObject("$group", groupFields); // Finally the $sort operation DBObject sort = new BasicDBObject("$sort", new BasicDBObject("average", -1)); // run aggregation List<DBObject> pipeline = Arrays.asList(match, project, group, sort); AggregationOutput output = coll.aggregate(pipeline); // Output the results for (DBObject result : output.results()) { System.out.println(result); } // Aggregation Cursor AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100) .outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build(); Cursor cursor = coll.aggregate(pipeline, aggregationOptions); while (cursor.hasNext()) { System.out.println(cursor.next()); } // clean up db.dropDatabase(); mongoClient.close(); }