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:com.nowellpoint.mongodb.persistence.impl.DocumentManagerImpl.java

License:Apache License

@Override
public void persist(Object document) {
    doumentManagerFactory.prePersist(document);
    String collectionName = doumentManagerFactory.resolveDocumentName(document.getClass());
    DBCollection collection = getDB().getCollection(collectionName);
    DBObject dbObject = doumentManagerFactory.convertObjectToDocument(document);
    try {//from  ww w. j  ava2 s .  co m
        collection.insert(dbObject);
    } catch (MongoException e) {
        if (e.getCode() == MongoExceptionCode.DOCUMENT_EXISTS) {
            throw new DocumentExistsException(e.getMessage());
        }
    }
    doumentManagerFactory.resolveId(document, dbObject.get(DocumentManagerFactoryImpl.ID));
    doumentManagerFactory.postPersist(document);
}

From source file:com.openbravo.data.loader.MongoDBBatchSentence.java

/**
 *
 * @param params/*from w ww  . j  a va2 s. co  m*/
 * @return
 * @throws BasicException
 */
@Override
public DataResultSet openExec(Object params) throws BasicException {
    try {
        BufferedReader br = new BufferedReader(getReader());

        String sLine;
        while ((sLine = br.readLine()) != null) {
            sLine = sLine.trim();
            if (!sLine.equals("") && !sLine.startsWith("--")) {

                String collection = sLine.split(";")[0].split("=")[1];
                String insertStatement = sLine.split(";")[1].replace('{', ' ').replace('}', ' ');
                insertStatement = insertStatement.trim();

                String[] mapSplit = insertStatement.split(",");
                BasicDBObject insertObject = new BasicDBObject();
                for (int i = 0; i < mapSplit.length; ++i) {
                    String[] keyValue = mapSplit[i].split(":");
                    if (keyValue[1].contains("$APP_ID"))
                        keyValue[1] = m_parameters.get("APP_ID");
                    else if (keyValue[1].contains("$APP_NAME"))
                        keyValue[1] = m_parameters.get("APP_NAME");
                    else if (keyValue[1].contains("$APP_VERSION"))
                        keyValue[1] = m_parameters.get("APP_VERSION");
                    if (keyValue[1].contains("$FILE")) {
                        String filepath = keyValue[1].trim().substring(6);
                        insertObject.append(keyValue[0].trim(), ImageUtils.getBytesFromResource(filepath));
                    } else {
                        insertObject.append(keyValue[0].trim(), keyValue[1].trim());
                    }
                }
                DBCollection dbCollection = m_s.getMongoDBDatabase().getCollection(collection);
                dbCollection.insert(insertObject);
            }
        }
    } catch (IOException ex) {

    }
    return new ExceptionsResultSet(new ArrayList());
}

From source file:com.openbravo.data.loader.MongoDBPreparedSentence.java

@Override
public DataResultSet openExec(Object params) throws BasicException {
    closeExec();//from  w ww .  j  a  va2  s.  c om

    DBCollection collection = m_s.getMongoDBDatabase().getCollection(m_collectionName);

    if (m_SerWrite != null) {
        if (m_insert)
            m_SerWrite.writeValues(new MongoDBPreparedSentencePars(m_insertDBObject, m_writeParamColumnMap),
                    params);
        else if (m_find)
            m_SerWrite.writeValues(new MongoDBPreparedSentencePars(m_findDBObject, m_writeParamColumnMap),
                    params);
        else if (m_update)
            m_SerWrite.writeValues(new MongoDBPreparedSentencePars(m_updateDBObject, m_writeParamColumnMap),
                    params);
    }

    if (!m_nullColumn.isEmpty())
        m_findDBObject.append(m_nullColumn, new BasicDBObject("$exists", true));

    if (m_lessThanColumn != null) {
        for (int i = 0; i < m_lessThanColumn.length; ++i) {
            Object lessThanValue = m_findDBObject.get(m_lessThanColumn[i]);
            m_findDBObject.removeField(m_lessThanColumn[i]);
            m_findDBObject.append(m_lessThanColumn[i], new BasicDBObject("$lt", lessThanValue));
        }
    }

    if (m_greaterThanColumn != null) {
        for (int i = 0; i < m_greaterThanColumn.length; ++i) {
            Object greaterThanValue = m_findDBObject.get(m_greaterThanColumn[i]);
            m_findDBObject.removeField(m_greaterThanColumn[i]);
            m_findDBObject.append(m_greaterThanColumn[i], new BasicDBObject("$gt", greaterThanValue));
        }
    }

    // Insert statement
    if (m_insert) {
        collection.insert(m_insertDBObject);
    } else if (m_find) {

        if (!m_sortColumn.isEmpty()) {
            m_dbCursor = collection.find(m_findDBObject).sort(new BasicDBObject(m_sortColumn, 1));
            return new MongoDBDataResultSet(m_dbCursor, m_readParamColumnMap, m_SerRead);
        }

        if (!m_maxColumn.isEmpty()) {
            Iterator<DBObject> it = collection
                    .aggregate(new BasicDBObject("$match", m_findDBObject),
                            new BasicDBObject("$group",
                                    new BasicDBObject("_id", "null").append("MAX",
                                            new BasicDBObject("$max", "$" + m_maxColumn))))
                    .results().iterator();
            //Iterator<DBObject> it = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "null").append("MAX", new BasicDBObject("$max", "$" + m_maxColumn)))).results().iterator();
            DBObject maxObject = new BasicDBObject();
            if (it.hasNext())
                maxObject = it.next();
            return new MongoDBDataResultSet(maxObject, m_readParamColumnMap, m_SerRead);
        }

        if (m_countAll) {
            Iterator<DBObject> it = collection
                    .aggregate(new BasicDBObject("$match", m_findDBObject), new BasicDBObject("$group",
                            new BasicDBObject("_id", "null").append("COUNT", new BasicDBObject("$sum", 1))))
                    .results().iterator();
            //Iterator<DBObject> it = collection.aggregate(new BasicDBObject("$group", new BasicDBObject("_id", "null").append("MAX", new BasicDBObject("$max", "$" + m_maxColumn)))).results().iterator();
            DBObject maxObject = new BasicDBObject();
            if (it.hasNext())
                maxObject = it.next();
            return new MongoDBDataResultSet(maxObject, m_readParamColumnMap, m_SerRead);
        }
        m_dbCursor = collection.find(m_findDBObject);
        return new MongoDBDataResultSet(m_dbCursor, m_readParamColumnMap, m_SerRead);
    } else if (m_update) {
        String findKey = ((String) m_writeParamColumnMap
                .get((Integer) m_writeParamColumnMap.keySet().toArray()[m_writeParamColumnMap.size() - 1]));
        String key = findKey.replace('s', ' ').trim();
        m_findDBObject.append(key, m_updateDBObject.get(findKey));

        // Remove the find criteria in the update object
        m_updateDBObject.remove(m_writeParamColumnMap
                .get((Integer) m_writeParamColumnMap.keySet().toArray()[m_writeParamColumnMap.size() - 1]));
        collection.findAndModify(m_findDBObject, null, null, true, m_updateDBObject, true, true);
        return new SentenceUpdateResultSet(0);
    }
    return null;
}

From source file:com.original.service.channel.config.Initializer.java

License:Open Source License

/**
 * /*w w  w. java 2s .co m*/
 * @param db
 * @param collectionName
 * @param fileName
 * @param force
 * @throws IOException
 */
private void initCollection(DB db, String collectionName, String fileName, boolean force) throws IOException {
    DBCollection collection = db.getCollection(collectionName);
    if (collection.getCount() > 0 && !force) {
        logger.info(collectionName + " had existed!");
        return;
    }

    if (force && collection.getCount() > 0) {
        collection.drop();
        logger.info("force to init, drop the collection:" + collectionName);
    }
    BufferedReader br = null;
    if (fileName.startsWith("/")) {
        InputStream is = Initializer.class.getResourceAsStream(fileName);
        br = new BufferedReader(new InputStreamReader(is));
    } else {
        br = new BufferedReader(new FileReader(fileName));
    }

    StringBuffer fileText = new StringBuffer();
    String line;
    while ((line = br.readLine()) != null) {
        fileText.append(line);
    }
    logger.info(collectionName + " Read:" + fileText);
    // System.out.println(profile);
    br.close();
    if (fileText != null) {
        // convert JSON to DBObject directly
        List<String> list = parseJsonItemsFile(fileText);
        for (String txt : list) {
            logger.info(collectionName + " init item:" + txt);
            DBObject dbObject = (DBObject) JSON.parse(txt);
            collection.insert(dbObject);
        }
    }
    logger.info(collectionName + " init Done:" + collection.count());
}

From source file:com.ovrhere.android.morseflash.ui.fragments.MainFragment.java

License:Apache License

private void insertIntoDB() {
    MongoClientURI URI = new MongoClientURI("mongodb://zaid:zaid@ds047802.mongolab.com:47802/aadhar");
    MongoClient client = null;/*from   www .  j a v a  2  s . c  o  m*/
    try {
        client = new MongoClient(URI);
        DB db = client.getDB("aadhar");
        DBCollection collection = db.getCollection("Sender");

        BasicDBObject document = new BasicDBObject();
        document.put("database", "aadhar");
        document.put("table", "Sender");

        BasicDBObject documentDetail = new BasicDBObject();
        documentDetail.put("Uid", "103");
        documentDetail.put("Amount", "1010");
        documentDetail.put("Pin", "" + UniqueCode);
        documentDetail.put("Status", "send");

        document.put("detail", documentDetail);

        collection.insert(document);

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

}

From source file:com.packtpub.mongo.chapter2.ArrayInsert.java

public static void main(String args[]) {
    try {/* www . java2s .  c om*/
        // To connect to mongodb server
        MongoClient mongoClient = new MongoClient(HOST, PORT);

        DB db = mongoClient.getDB("semaine09");

        DBCollection coll = db.getCollection("contacts");

        List<DBObject> kids = new ArrayList<>();
        kids.add(new BasicDBObject("name", "mike"));
        kids.add(new BasicDBObject("name", "faye"));

        DBObject doc = new BasicDBObject("name", "john").append("age", 35).append("kids", kids).append("info",
                new BasicDBObject("email", "john@mail.com").append("phone", "876-134-667"));
        coll.insert(doc);

    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

/**
 * {@inheritDoc}//w ww.  j ava 2  s. co m
 */
@Override
public <T extends Model> void insert(T object) {
    DBCollection dbCollection = this.getCollection(object.getClass());
    MongoModelSerializer serializer = this.getSerializer(object.getClass());
    DBObject serialize = serializer.serialize(object);

    WriteResult insert = dbCollection.insert(serialize);
    setResult(insert);

}

From source file:com.redhat.lightblue.metadata.mongo.MetadataCache.java

License:Open Source License

/**
 * Update the collection version in db, and invalidate cache
 *//*w w  w  .j  av a  2  s .c om*/
public synchronized void updateCollectionVersion(DBCollection collection) {
    BasicDBObject query = new BasicDBObject(MongoMetadata.LITERAL_ID, LITERAL_COLL_VER);
    BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject(LITERAL_COLL_VER, 1));
    int nUpdated;
    try {
        WriteResult r = collection.update(query, update);
        nUpdated = r.getN();
    } catch (Exception e) {
        nUpdated = 0;
    }
    if (nUpdated == 0) {
        // Try to ins
        BasicDBObject doc = new BasicDBObject(MongoMetadata.LITERAL_ID, LITERAL_COLL_VER);
        doc.put(LITERAL_COLL_VER, 0l);
        try {
            collection.insert(doc);
        } catch (Exception e) {
        }
    }
    cache.clear();
}

From source file:com.ricardolorenzo.identity.user.impl.UserIdentityManagerMongoDB.java

License:Open Source License

/**
 * All the scripts should have the following format:
 *
 * {/*w w  w .  j  a va  2 s .co  m*/
 *    database.collection: {
 *        operation: insert|update|find|aggregate|delete
 *        query: {}
 *    }
 * }
 *
 * For update operations, you should specify the following:
 *
 * query: {
 *     find: {}
 *     update: {}
 * }
 */
private List<DBObject> runQueryScript(final String scriptType, final Map<String, Object[]> attributes)
        throws IdentityException {
    List<DBObject> results = new ArrayList<>();
    try {
        DB database = mongoClient.getDB(this.properties.getProperty("mongodb.database"));
        final ScriptCollection sc = getScriptCollection();
        if (sc.hasScript(scriptType)) {
            final String scriptContent = sc.getScript(scriptType);
            String query = createQueryFromScript(scriptContent, attributes);
            DBObject collectionOperation = DBObject.class.cast(JSON.parse(query));

            for (String collection : collectionOperation.keySet()) {
                if (!database.collectionExists(collection)) {
                    throw new IdentityException("collection [" + collection + "] does not exists");
                }

                DBObject dbObject = DBObject.class.cast(collectionOperation.get(collection));
                if (!dbObject.containsField("operation")) {
                    throw new IdentityException("operation field not specified");
                }

                String dbOperation = String.class.cast(dbObject.get("operation")).toLowerCase();
                if (!OPERATIONS.contains(dbOperation)) {
                    throw new IdentityException("operation [" + dbOperation + "] not supported");
                }

                DBObject dbQuery = DBObject.class.cast(dbObject.get("query"));
                if (dbQuery == null) {
                    throw new IdentityException("query field not specified");
                }

                DBCollection coll = database.getCollection(collection);
                switch (dbOperation) {
                case "insert": {
                    coll.insert(dbQuery);
                }
                case "update": {
                    if (!dbObject.containsField("find")) {
                        throw new IdentityException("find field not found inside the update operation");
                    }
                    if (!dbObject.containsField("update")) {
                        throw new IdentityException("update field not found inside the update operation");
                    }
                    DBObject dbUpdateFind = DBObject.class.cast(dbQuery.get("find"));
                    DBObject dbUpdateFields = DBObject.class.cast(dbQuery.get("update"));
                    coll.update(dbUpdateFind, dbUpdateFields, false, false);
                }
                case "delete": {
                    coll.remove(dbQuery);
                }
                case "find": {
                    DBCursor cursor = coll.find(dbQuery);
                    while (cursor.hasNext()) {
                        results.add(cursor.next());
                    }
                }
                case "aggregate": {
                    List<DBObject> aggregate = new ArrayList<DBObject>();
                    aggregate.add(dbQuery);
                    for (DBObject o : coll.aggregate(aggregate).results()) {
                        results.add(o);
                    }
                }
                }
            }
            return results;
        }
    } catch (final NoSuchAlgorithmException e) {
        throw new IdentityException(e.getMessage());
    } finally {
        /**
         * TODO close cursors
         */
    }
    return null;
}

From source file:com.sample.MyGroceryListServlet.java

License:Open Source License

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *///ww w  .  j av a 2  s  . c o  m
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Reference: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/#getting-started-with-java-driver

    String envVars = System.getenv("VCAP_SERVICES");

    DBObject dbO = (DBObject) JSON.parse(envVars);
    String parsedString = dbO.get("mongodb").toString();

    // Remove trailing and starting array brackets (otherwise it won't be valid JSON)
    parsedString = parsedString.replaceFirst("\\[ ", "");
    parsedString = parsedString.replaceFirst("\\]$", "");

    // Get the credentials
    dbO = (DBObject) JSON.parse(parsedString);
    parsedString = dbO.get("credentials").toString();

    // For debugging only
    // System.out.println(parsedString);

    dbO = (DBObject) JSON.parse(parsedString);

    System.out.println("Host name : " + dbO.get("hostname"));
    String hostName = dbO.get("hostname").toString();
    int port = Integer.parseInt(dbO.get("port").toString());
    String dbName = dbO.get("db").toString();
    String userName = dbO.get("username").toString();
    String password = dbO.get("password").toString();

    Mongo mongoClient = new Mongo(hostName, port);

    DB db = mongoClient.getDB(dbName);
    db.authenticate(userName, password.toCharArray());

    // Clean up old entries
    DBCollection coll = db.getCollection("testCollection");
    coll.drop();

    BasicDBObject lastAddedObject = null;
    for (String curItem : myGroceryList) {
        lastAddedObject = new BasicDBObject("i", curItem);
        coll.insert(lastAddedObject);
    }
    response.getWriter().println("<b>My grocery list is:</b>");

    coll.remove(lastAddedObject);
    DBCollection loadedCollection = db.getCollection("testCollection");
    DBCursor cursor = loadedCollection.find();
    try {
        response.getWriter().println("<ul>");
        while (cursor.hasNext()) {
            response.getWriter().println("<li>" + cursor.next().get("i") + "</li>");
        }
        response.getWriter().println("</ul>");
    } finally {
        cursor.close();
    }
}