Example usage for com.mongodb.client MongoCollection insertOne

List of usage examples for com.mongodb.client MongoCollection insertOne

Introduction

In this page you can find the example usage for com.mongodb.client MongoCollection insertOne.

Prototype

void insertOne(TDocument document);

Source Link

Document

Inserts the provided document.

Usage

From source file:MultiSources.Fusionner.java

public void exportAllCandsMongoDB(ArrayList<NodeCandidate> allCands) {
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("evals_Triticum");
    db.drop();/*from www  .  j  av  a 2  s . co m*/
    MongoCollection<Document> collection = db.getCollection("triticumCandidate");
    MongoCollection<Document> collectionRel = db.getCollection("triticumICHR");
    MongoCollection<Document> collectionType = db.getCollection("triticumTypeCandidate");
    MongoCollection<Document> collectionLabel = db.getCollection("triticumLabelCandidate");
    for (NodeCandidate nc : allCands) {
        if (nc.isIndividual()) {
            collection.insertOne(new Document(nc.toDBObject()));
            IndividualCandidate ic = (IndividualCandidate) nc;
            for (ArcCandidate ac : ic.getAllArcCandidates()) {
                String prop = ac.getDataProp();
                if (prop.startsWith("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")) {
                    collectionType.insertOne(new Document(ac.toDBObject()));
                } else if (prop.startsWith("http://ontology.irstea.fr/AgronomicTaxon#hasHigherRank")) {
                    collectionRel.insertOne(new Document(ac.toDBObject()));
                }
                for (LabelCandidate lc : ic.getLabelCandidates()) {
                    collectionLabel.insertOne(new Document(lc.toDBObject()));
                }
            }
        }

    }
}

From source file:mx.com.tecnomotum.testmongodb.Principal.java

public static void main(String args[]) {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    MongoDatabase db = mongoClient.getDatabase("test");
    MongoCollection<Document> coleccion = db.getCollection("restaurants");
    long totalElementos = coleccion.count();
    System.out.println("Total de elementos en la coleccin:" + totalElementos);

    // Obtener el primer elemento de la coleccin
    Document myDoc = coleccion.find().first();
    System.out.println("Primer object:" + myDoc.toJson());

    //Crear y aadir un nuevo documento a la coleccin
    Document nuevoDoc = new Document("name", "CARLITOS buf");
    nuevoDoc.append("borough", "Elvia");
    nuevoDoc.append("cuisine", "Gourmet");
    List<Document> puntuaciones = new ArrayList<>();
    Document punt = new Document();
    punt.append("grade", "A");
    punt.append("date", new Date());
    punt.append("score", 9);
    puntuaciones.add(punt);// ww  w. j a  v a  2s.  com
    nuevoDoc.append("grades", puntuaciones);
    coleccion.insertOne(nuevoDoc);
    System.out.println("Total de elementos en la coleccin:" + coleccion.count());

    //OBtener un objeto de una coleccin
    Document objetoResp = coleccion.find(eq("name", "CARLITOS buf")).first();
    System.out.println("OBjeto encontrado:" + objetoResp.toJson());

    //OBtener la proyeccin del documento
    Document objetoResp2 = coleccion.find(eq("name", "CARLITOS buf"))
            .projection(fields(excludeId(), include("name"), include("grades.score"))).first();
    System.out.println("OBjeto encontrado:" + objetoResp2.toJson());

    //OBtener conjuntos de datos
    Block<Document> printBlock = new Block<Document>() {

        @Override
        public void apply(final Document doc) {
            System.out.println(doc.toJson());
        }
    };

    coleccion.find(eq("cuisine", "Hamburgers")).projection(fields(excludeId(), include("name")))
            .sort(Sorts.ascending("name")).forEach(printBlock);

}

From source file:net.acesinc.nifi.processors.mongodb.PutMongoWithDuplicateCheck.java

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    StopWatch totalWatch = new StopWatch(true);
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;//from  ww w  .  j  a v a  2  s  .c om
    }

    final ProcessorLog logger = getLogger();

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final WriteConcern writeConcern = getWriteConcern(context);

    final MongoCollection<Document> collection = getCollection(context).withWriteConcern(writeConcern);

    try {
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(final InputStream in) throws IOException {
                StreamUtils.fillBuffer(in, content, true);
            }
        });

        // parse
        final Document doc = Document.parse(new String(content, charset));

        StopWatch insertWatch = new StopWatch(true);
        collection.insertOne(doc);
        insertWatch.stop();
        logger.info("inserted {} into MongoDB in {} ms",
                new Object[] { flowFile, insertWatch.getDuration(TimeUnit.MILLISECONDS) });

        session.getProvenanceReporter().send(flowFile, context.getProperty(URI).getValue());
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        if (e instanceof MongoWriteException) {
            if (e.getMessage().contains("duplicate key")) {
                session.getProvenanceReporter().send(flowFile, context.getProperty(URI).getValue());
                session.transfer(flowFile, REL_ALREADY_EXISTS);
                context.yield();
            }
        } else {
            logger.error("Failed to insert {} into MongoDB due to {}", new Object[] { flowFile, e }, e);
            //else, some other error that we don't handle. 
            session.transfer(flowFile, REL_FAILURE);
            context.yield();
        }
    }
    totalWatch.stop();
    logger.info("PutMongo took: " + totalWatch.getDuration(TimeUnit.MILLISECONDS) + "ms");
}

From source file:net.liaocy.ml4j.db.Mongo.java

public static void save(MongoCollection<Document> collection, Document document) {
    Object id = document.get("_id");
    if (id == null) {
        collection.insertOne(document);
    } else {//from   ww  w . j  ava2  s .  c o m
        collection.replaceOne(eq("_id", id), document, new UpdateOptions().upsert(true));
    }
}

From source file:net.netzgut.integral.mongo.internal.services.MongoODMImplementation.java

License:Apache License

@Override
public <T extends Serializable> void persist(T entity) {
    Class<? extends Serializable> entityClass = entity.getClass();
    MongoCollection<Document> collection = this.mongo.getCollection(entityClass);
    Document document = this.converter.documentFrom(entity);
    collection.insertOne(document);
}

From source file:nl.syntouch.oracle.adapter.cloud.mongodb.sample.MongoDBSample.java

License:Apache License

public static void main(String[] args) {
    // connect to MongoDB at localhost:27017
    MongoClient mongoClient = new MongoClient();

    // switch to test db
    MongoDatabase database = mongoClient.getDatabase("test");

    // drop test collection (note the collection will always be created by the getCollection command)
    MongoCollection<Document> collection = database.getCollection("test");
    collection.drop();//from w w w .  j  a  v  a2 s .  co m

    // create a new collection
    collection = database.getCollection("test");

    // create BSON document and save it
    Document doc = new Document().append("field1", "value1");
    collection.insertOne(doc);
    System.out.println(doc.toString());

    Document queryDoc1 = new Document().append("_id", doc.get("_id"));
    System.out.println(collection.find(queryDoc1).first().toString());

    Document queryDoc2 = new Document().append("field1", doc.get("field1"));
    System.out.println(collection.find(queryDoc2).first().toString());
}

From source file:org.apache.eagle.alert.metadata.impl.MongoMetadataDaoImpl.java

License:Apache License

private <T> OpResult addOne(MongoCollection<Document> collection, T t) {
    OpResult result = new OpResult();
    String json = "";
    try {/*from  w  w w  .j av  a 2  s .  com*/
        json = mapper.writeValueAsString(t);
        collection.insertOne(Document.parse(json));
        result.code = 200;
        result.message = String.format("add one document [%s] to collection [%s] succeed!", json,
                collection.getNamespace());
        LOG.info(result.message);
    } catch (Exception e) {
        result.code = 400;
        result.message = e.getMessage();
        LOG.error(String.format("Add one document [%s] to collection [%s] failed!", json,
                collection.getNamespace()), e);
    }
    return result;
}

From source file:org.apache.metamodel.mongodb.mongo3.MongoDbInsertionBuilder.java

License:Apache License

@Override
public void execute() throws MetaModelException {
    final Column[] columns = getColumns();
    final Object[] values = getValues();

    final Document doc = new Document();

    for (int i = 0; i < values.length; i++) {
        Object value = values[i];
        if (value != null) {
            doc.put(columns[i].getName(), value);
        }/*w w w .ja v a 2 s .  c o m*/
    }

    final MongoDbUpdateCallback updateCallback = getUpdateCallback();
    final MongoCollection<Document> collection = updateCallback.getCollection(getTable().getName());
    final WriteConcern writeConcern = updateCallback.getWriteConcernAdvisor().adviceInsert(collection, doc);
    collection.withWriteConcern(writeConcern);

    collection.insertOne(doc);
    logger.info("Document has been inserted");
}

From source file:org.apache.nifi.processors.mongodb.PutMongo.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;/* w ww.  jav  a2  s  .  c o  m*/
    }

    final ComponentLog logger = getLogger();

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String mode = context.getProperty(MODE).getValue();
    final String updateMode = context.getProperty(UPDATE_MODE).getValue();
    final WriteConcern writeConcern = getWriteConcern(context);

    final MongoCollection<Document> collection = getCollection(context, flowFile)
            .withWriteConcern(writeConcern);

    try {
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, in -> StreamUtils.fillBuffer(in, content, true));

        // parse
        final Object doc = (mode.equals(MODE_INSERT)
                || (mode.equals(MODE_UPDATE) && updateMode.equals(UPDATE_WITH_DOC.getValue())))
                        ? Document.parse(new String(content, charset))
                        : JSON.parse(new String(content, charset));

        if (MODE_INSERT.equalsIgnoreCase(mode)) {
            collection.insertOne((Document) doc);
            logger.info("inserted {} into MongoDB", new Object[] { flowFile });
        } else {
            // update
            final boolean upsert = context.getProperty(UPSERT).asBoolean();
            final String updateKey = context.getProperty(UPDATE_QUERY_KEY).getValue();

            Object keyVal = ((Map) doc).get(updateKey);
            if (updateKey.equals("_id") && ObjectId.isValid(((String) keyVal))) {
                keyVal = new ObjectId((String) keyVal);
            }

            final Document query = new Document(updateKey, keyVal);

            if (updateMode.equals(UPDATE_WITH_DOC.getValue())) {
                collection.replaceOne(query, (Document) doc, new UpdateOptions().upsert(upsert));
            } else {
                BasicDBObject update = (BasicDBObject) doc;
                update.remove(updateKey);
                collection.updateOne(query, update, new UpdateOptions().upsert(upsert));
            }
            logger.info("updated {} into MongoDB", new Object[] { flowFile });
        }

        session.getProvenanceReporter().send(flowFile, getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        logger.error("Failed to insert {} into MongoDB due to {}", new Object[] { flowFile, e }, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}

From source file:org.auraframework.test.perf.PerfResultsUtil.java

License:Apache License

public static void writeToDb(PerfMetrics metrics, String test) {
    try {/*from   w  ww  .j a  v  a  2s . c om*/
        MongoClient mongo = getMongoClient();
        if (mongo != null) {
            MongoDatabase db = mongo.getDatabase("performance");
            MongoCollection<Document> runs = db.getCollection("testRun");
            JSONObject json = metrics.toJSONObject();
            Document doc = Document.parse(json.toString());
            doc.append("testName", test);
            doc.append("run", RUN_TIME);
            runs.insertOne(doc);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}