Example usage for com.mongodb DBCollection insert

List of usage examples for com.mongodb DBCollection insert

Introduction

In this page you can find the example usage for com.mongodb DBCollection insert.

Prototype

public WriteResult insert(final List<? extends DBObject> documents) 

Source Link

Document

Insert documents into a collection.

Usage

From source file:org.benjp.services.mongodb.UserServiceImpl.java

License:Open Source License

public void setAsAdmin(String user, boolean isAdmin) {
    DBCollection coll = db().getCollection(M_USERS_COLLECTION);
    BasicDBObject query = new BasicDBObject();
    query.put("user", user);
    DBCursor cursor = coll.find(query);//ww  w.  j  av a  2 s.com
    if (cursor.hasNext()) {
        DBObject doc = cursor.next();
        doc.put("isSupportAdmin", isAdmin);
        coll.save(doc, WriteConcern.SAFE);
    } else {
        BasicDBObject doc = new BasicDBObject();
        doc.put("_id", user);
        doc.put("user", user);
        doc.put("isSupportAdmin", isAdmin);
        coll.insert(doc);
    }
}

From source file:org.chililog.server.data.Controller.java

License:Apache License

/**
 * Saves the user into mongoDB/*from  ww w.j a v  a  2s  .c om*/
 * 
 * @param db
 *            MongoDb connection
 * @param businessObject
 *            Business object to save
 * @throws ChiliLogException
 *             if there is an error during saving
 */
public void save(DB db, BO businessObject) throws ChiliLogException {
    if (db == null) {
        throw new NullArgumentException("db");
    }
    if (businessObject == null) {
        throw new NullArgumentException("businessObject");
    }

    try {
        DBObject obj = businessObject.toDBObject();
        DBCollection coll = db.getCollection(this.getDBCollectionName());
        if (businessObject.isExistingRecord()) {
            long recordVersion = businessObject.getDocumentVersion();
            obj.put(BO.DOCUMENT_VERSION_FIELD_NAME, recordVersion + 1);

            BasicDBObject query = new BasicDBObject();
            query.put(BO.DOCUMENT_ID_FIELD_NAME, obj.get(BO.DOCUMENT_ID_FIELD_NAME));
            query.put(BO.DOCUMENT_VERSION_FIELD_NAME, recordVersion);

            coll.update(query, obj, false, false, this.getDBWriteConern());
        } else {
            obj.put(BO.DOCUMENT_VERSION_FIELD_NAME, (long) 1);
            coll.insert(obj);
        }
    } catch (MongoException ex) {
        throw new ChiliLogException(ex, Strings.MONGODB_SAVE_ERROR, ex.getMessage());
    }
}

From source file:org.cvbase.service.mongodb.MongodbService.java

License:Open Source License

/**
 * {@inheritDoc}//from ww  w.  ja  va  2 s . c om
 *
 * This is an implementation for Mongo DB.
 */
@Override
public <T extends Model> T create(T t) {
    if (t == null) {
        return null;
    }

    BasicDBObject object = new BasicDBObject();

    Class<?> type = t.getClass();
    DBCollection coll = db.getCollection(type.getSimpleName());

    Long key = t.getOid();
    if (key == null) {
        // Set a new object identifier.
        DBCursor cursor = coll.find();
        key = (long) cursor.size() + 1;
        cursor.close();
    }
    t.setOid(key);

    if (find(t.getClass(), key) != null) {
        return null;
    }

    List<Field> fields = getDeclaredFields(type, new LinkedList<Field>());
    List<Method> methods = getDeclaredMethods(type, new LinkedList<Method>());

    for (Field field : fields) {
        for (Method method : methods) {
            // Call a getter method.
            if (("get" + field.getName()).equalsIgnoreCase(method.getName())) {
                try {
                    object.put(field.getName(), method.invoke(t));
                } catch (IllegalAccessException e) {
                    LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                } catch (InvocationTargetException e) {
                    LOG.log(Level.WARNING, "Call of the method " + method.getName() + " is failed", e);
                }
                break;
            }
        }
    }

    try {
        LOG.log(Level.INFO, "{0}", t);
        WriteResult writeResult = coll.insert(object);
        if (writeResult.getError() != null) {
            LOG.log(Level.WARNING, "Insertion of {0} is failed.", t);
        }
    } catch (MongoException e) {
        LOG.log(Level.SEVERE, "Insertion of " + t + " is failed.", e);
    }

    return t;
}

From source file:org.datanucleus.store.mongodb.valuegenerator.IncrementGenerator.java

License:Open Source License

protected ValueGenerationBlock reserveBlock(long size) {
    if (size < 1) {
        return null;
    }// w ww.j ava  2s.co m

    List oids = new ArrayList();
    ManagedConnection mconn = connectionProvider.retrieveConnection();
    try {
        DB db = (DB) mconn.getConnection();
        if (!storeMgr.isAutoCreateTables() && !db.collectionExists(collectionName)) {
            throw new NucleusUserException(LOCALISER.msg("040011", collectionName));
        }

        // Create the collection if not existing
        DBCollection dbCollection = db.getCollection(collectionName);
        BasicDBObject query = new BasicDBObject();
        query.put("field-name", key);
        DBCursor curs = dbCollection.find(query);
        if (curs == null || !curs.hasNext()) {
            // No current entry for this key, so add initial entry
            long initialValue = 0;
            if (properties.containsKey("key-initial-value")) {
                initialValue = Long.valueOf(properties.getProperty("key-initial-value")) - 1;
            }
            BasicDBObject dbObject = new BasicDBObject();
            dbObject.put("field-name", key);
            dbObject.put(INCREMENT_COL_NAME, new Long(initialValue));
            dbCollection.insert(dbObject);
        }

        // Create the entry for this field if not existing
        query = new BasicDBObject();
        query.put("field-name", key);
        curs = dbCollection.find(query);
        DBObject dbObject = curs.next();

        Long currentValue = (Long) dbObject.get(INCREMENT_COL_NAME);
        long number = currentValue.longValue();
        for (int i = 0; i < size; i++) {
            oids.add(number + i + 1);
        }
        dbObject.put(INCREMENT_COL_NAME, new Long(number + size));
        dbCollection.save(dbObject);
    } finally {
        connectionProvider.releaseConnection();
    }

    return new ValueGenerationBlock(oids);
}

From source file:org.eclipse.birt.report.engine.dataextraction.mongodb.MongoDataExtractionUtil.java

License:Open Source License

public static void insertCollection(DBCollection collection, LinkedList<DBObject> basicDBList)
        throws BirtException {
    try {/*from  ww w .j  a  v a 2 s. c  o m*/
        collection.insert(basicDBList);
    } catch (Exception e) {
        client.close();
        throw new BirtException(e.getMessage());
    }
}

From source file:org.eclipse.birt.report.engine.emitter.mongodb.MongoDbEmitter.java

License:Open Source License

private void writeOutput(String tableName) throws BirtException {
    if (tableName == null || "".equals(tableName.trim())) {
        return;/*from   www .  j a  v a  2s  .c  om*/
    }
    // write json object list to this table/collection
    DBCollection collection = mongoDatabase.getCollection(tableName);
    if (!dbObjectList.isEmpty()) {
        collection.insert(dbObjectList);
        dbObjectList.clear();
    }
    if (!groupObjectList.isEmpty()) {
        collection.insert(groupObjectList);
        groupObjectList.clear();
    }
}

From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java

License:Open Source License

/**
 *  Insert an object's field with only one level of nesting. The object's class should  only
 *  have public data fields when calling this function. For example, create a class A{String b; Integer b},
 *  assign values after instantiating the object and pass it to the function
 * @param record Object from which to extract fields and values
 * @param database Database name/*from  ww w .ja v  a 2s  .  c  o m*/
 * @param collection Collection name
 * @throws TotalADSDBMSException,
 * @throws IllegalAccessException
 * @throws IllegalAccessException
 */
public void insert(Object record, String database, String collection)
        throws TotalADSDBMSException, IllegalAccessException, IllegalAccessException {

    WriteResult writeRes = null;
    String exception = "";
    DB db = mongoClient.getDB(database);
    DBCollection coll = db.getCollection(collection);

    BasicDBObject document = new BasicDBObject();
    extractKeysAndValuesfromTheObject(record, document);

    try {
        writeRes = coll.insert(document);
    } catch (MongoException e) {
        exception = "Caught MongoException cause: " + e.getMessage();
    }

    CommandResult cmdResult = writeRes.getLastError();
    if (!cmdResult.ok())
        exception += "\n error : " + cmdResult.getErrorMessage();

    if (!exception.isEmpty())
        throw new TotalADSDBMSException(exception);

}

From source file:org.eclipse.linuxtools.tmf.totalads.dbms.DBMS.java

License:Open Source License

/**
 * Inserts an object in the form of JSON representation into the database. Any kind of complex
 *  data structure can be converted to JSON  using gson library and passed to this function 
 * @param database Database name/* ww  w.j a v a  2s . c om*/
 * @param jsonObject JSON Object
 * @param collection Collection name in which to insert 
 * @throws TotalADSDBMSException
 */
public void insertUsingJSON(String database, JsonObject jsonObject, String collection)
        throws TotalADSDBMSException {
    try {
        DB db = mongoClient.getDB(database);
        DBCollection coll = db.getCollection(collection);
        BasicDBObject obj = (BasicDBObject) JSON.parse(jsonObject.toString());
        coll.insert(obj);
    } catch (Exception ex) { // If there is any exception here cast it as DBMS exception
        throw new TotalADSDBMSException(ex.getMessage());
    }
}

From source file:org.eclipse.tracecompass.totalads.dbms.MongoDBMS.java

License:Open Source License

@Override
public void insertUsingJSON(String database, JsonObject jsonObject, String collection)
        throws TotalADSDBMSException {
    try {// w  w  w .j  av a2 s  .  c  o m
        DB db = mongoClient.getDB(database);
        DBCollection coll = db.getCollection(collection);
        BasicDBObject obj = (BasicDBObject) JSON.parse(jsonObject.toString());
        coll.insert(obj);
    } catch (Exception ex) { // If there is any exception here, cast it as
                             // IDataAccessObject exception
        throw new TotalADSDBMSException(ex.getMessage());
    }
}

From source file:org.eclipselabs.emongo.example.ExampleComponent.java

License:Open Source License

public void activate() {
    DB database = mongoDatabaseProvider.getDB();
    DBCollection collection = database.getCollection("items");
    collection.drop();//  w w w  .j  a  v  a 2s.  co m

    for (int i = 0; i < 10; i++)
        collection.insert(new BasicDBObject("x", i));

    DBCursor cursor = collection.find();

    while (cursor.hasNext())
        System.out.print(cursor.next().get("x") + " ");

    System.out.println();
    collection.drop();
}