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.springframework.data.document.mongodb.MongoTemplate.java

License:Apache License

protected List<ObjectId> insertDBObjectList(String collectionName, final List<DBObject> dbDocList) {

    if (dbDocList.isEmpty()) {
        return Collections.emptyList();
    }/*from  ww  w  . j  a  v a2s. c  o m*/

    //TODO: Need to move this to more central place
    for (DBObject dbDoc : dbDocList) {
        if (dbDoc.containsField("_id")) {
            if (dbDoc.get("_id") instanceof String) {
                ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id"));
                if (oid != null) {
                    dbDoc.put("_id", oid);
                }
            }
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("insert list of DBObjects containing " + dbDocList.size() + " items");
    }
    execute(collectionName, new CollectionCallback<Void>() {
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            if (writeConcern == null) {
                collection.insert(dbDocList);
            } else {
                collection.insert(dbDocList.toArray((DBObject[]) new BasicDBObject[dbDocList.size()]),
                        writeConcern);
            }
            return null;
        }
    });

    List<ObjectId> ids = new ArrayList<ObjectId>();
    for (DBObject dbo : dbDocList) {
        Object id = dbo.get(ID);
        if (id instanceof ObjectId) {
            ids.add((ObjectId) id);
        } else {
            // no id was generated
            ids.add(null);
        }
    }
    return ids;
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

protected Object insertDBObject(final String collectionName, final DBObject dbDoc, final Class<?> entityClass) {

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Inserting DBObject containing fields: {} in collection: {}", dbDoc.keySet(),
                collectionName);// www. j a  va2s .  c  o  m
    }

    return execute(collectionName, new CollectionCallback<Object>() {
        public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT, collectionName,
                    entityClass, dbDoc, null);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            WriteResult writeResult = writeConcernToUse == null ? collection.insert(dbDoc)
                    : collection.insert(dbDoc, writeConcernToUse);
            handleAnyWriteResultErrors(writeResult, dbDoc, MongoActionOperation.INSERT);
            return dbDoc.get(ID_FIELD);
        }
    });
}

From source file:org.springframework.data.mongodb.core.MongoTemplate.java

License:Apache License

protected List<ObjectId> insertDBObjectList(final String collectionName, final List<DBObject> dbDocList) {
    if (dbDocList.isEmpty()) {
        return Collections.emptyList();
    }/* w ww. java  2 s . c om*/

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Inserting list of DBObjects containing {} items", dbDocList.size());
    }

    execute(collectionName, new CollectionCallback<Void>() {
        public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {
            MongoAction mongoAction = new MongoAction(writeConcern, MongoActionOperation.INSERT_LIST,
                    collectionName, null, null, null);
            WriteConcern writeConcernToUse = prepareWriteConcern(mongoAction);
            WriteResult writeResult = writeConcernToUse == null ? collection.insert(dbDocList)
                    : collection.insert(dbDocList.toArray((DBObject[]) new BasicDBObject[dbDocList.size()]),
                            writeConcernToUse);
            handleAnyWriteResultErrors(writeResult, null, MongoActionOperation.INSERT_LIST);
            return null;
        }
    });

    List<ObjectId> ids = new ArrayList<ObjectId>();
    for (DBObject dbo : dbDocList) {
        Object id = dbo.get(ID_FIELD);
        if (id instanceof ObjectId) {
            ids.add((ObjectId) id);
        } else {
            // no id was generated
            ids.add(null);
        }
    }
    return ids;
}

From source file:org.springframework.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

@Override
protected Object generateIdentifier(final PersistentEntity persistentEntity, final DBObject nativeEntry) {
    return mongoTemplate.execute(new DbCallback<Object>() {
        @Override/* w w  w.  j ava 2 s.c  o  m*/
        public Object doInDB(DB con) throws MongoException, DataAccessException {

            String collectionName = getCollectionName(persistentEntity, nativeEntry);

            DBCollection dbCollection = con.getCollection(collectionName + NEXT_ID_SUFFIX);

            // If there is a numeric identifier then we need to rely on optimistic concurrency controls to obtain a unique identifer
            // sequence. If the identifier is not numeric then we assume BSON ObjectIds.
            if (hasNumericalIdentifier) {
                while (true) {
                    DBCursor result = dbCollection.find().sort(new BasicDBObject(MONGO_ID_FIELD, -1)).limit(1);

                    long nextId;
                    if (result.hasNext()) {
                        final Long current = getMappingContext().getConversionService()
                                .convert(result.next().get(MONGO_ID_FIELD), Long.class);
                        nextId = current + 1;
                    } else {
                        nextId = 1;
                    }

                    nativeEntry.put(MONGO_ID_FIELD, nextId);
                    final WriteResult writeResult = dbCollection.insert(nativeEntry);
                    final CommandResult lastError = writeResult.getLastError();
                    if (lastError.ok()) {
                        break;
                    } else {
                        final Object code = lastError.get("code");
                        // duplicate key error try again
                        if (code != null && code.equals(11000)) {
                            continue;
                        }
                        break;
                    }
                }

                return nativeEntry.get(MONGO_ID_FIELD);
            } else {
                ObjectId objectId = ObjectId.get();
                if (ObjectId.class.isAssignableFrom(persistentEntity.getIdentity().getType())) {
                    nativeEntry.put(MONGO_ID_FIELD, objectId);
                    return objectId;
                } else {
                    String stringId = objectId.toString();
                    nativeEntry.put(MONGO_ID_FIELD, stringId);
                    return stringId;
                }
            }
        }
    });
}

From source file:org.springframework.datastore.mapping.mongo.engine.MongoEntityPersister.java

License:Apache License

@Override
protected Object storeEntry(final PersistentEntity persistentEntity, final Object storeId,
        final DBObject nativeEntry) {
    return mongoTemplate.execute(new DbCallback<Object>() {
        @Override/*from  w  w w  .  j  a  v a 2 s  .c o m*/
        public Object doInDB(DB con) throws MongoException, DataAccessException {

            String collectionName = getCollectionName(persistentEntity, nativeEntry);

            DBCollection dbCollection = con.getCollection(collectionName);
            nativeEntry.put(MONGO_ID_FIELD, storeId);
            dbCollection.insert(nativeEntry);

            return nativeEntry.get(MONGO_ID_FIELD);
        }
    });
}

From source file:org.swissbib.srw.SRWUpdateService.java

License:Open Source License

private void logMessages(String messageID, String actionText) {

    final String ACTIVE_MONGO_COLLECTION = "activeMongoCollection";
    final String LOG_MESSAGES = "logMessages";

    try {/*from   w  w w. java2s. co  m*/
        MessageContext mc = MessageContext.getCurrentMessageContext();
        //String test = mc.getAxisService().getParameter(LOG_MESSAGES).getValue().toString();
        if (Boolean.valueOf(mc.getAxisService().getParameter(LOG_MESSAGES).getValue().toString())) {

            DBCollection mongoCollection = (DBCollection) mc.getAxisService()
                    .getParameter(ACTIVE_MONGO_COLLECTION).getValue();

            //SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
            SimpleDateFormat simpleFormatDay = new SimpleDateFormat("yyyy-MM-dd");
            //SimpleDateFormat exactHumanReadbleTime = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
            SimpleDateFormat exactHumanReadbleTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

            Date currentDate = new Date();

            // yyyy-mm-dd hh:mm:ss.fffffffff

            //String td = simpleFormatDay.format(currentDate);
            //String tmE = exactHumanReadbleTime.format(currentDate);

            //long currentTimestamp = currentDate.getTime();

            //Parameter delPattern = mc.getAxisService().getParameter(DEL_PATTERN);

            //Pattern p =  (Pattern) delPattern.getValue();

            /*
            actually we see the problem that our data-hub sends SRU messages containing a create or replace
            SRU message although the record is indicated as deleted in the leader tag.
            These records are going to be deleted on the SearchIndex (look at serializeRecord method) and the original action text is extended
            to mark such cases in the logs
            */
            //if (leaderCharPos6.equals("d") && ! p.matcher(actionText).find()) {
            //    actionText = actionText + ":sbdelete";
            //}

            BasicDBObject doc = new BasicDBObject("id", messageID).append("action", actionText)
                    .append("updateDay", simpleFormatDay.format(currentDate)).
                    //append("marcStatus", leaderCharPos6).
                    append("timestamp", currentDate.getTime())
                    .append("readTime", exactHumanReadbleTime.format(currentDate));

            mongoCollection.insert(doc);

        }
    } catch (Throwable thr) {
        System.out.println("Exception  trying to write log message into Mongo DB for id: " + messageID
                + " action: " + actionText);
        System.out.print(thr.getMessage());
    }

}

From source file:org.unitedid.shibboleth.attribute.resolver.provider.dataConnector.MongoDbDataConnector.java

License:Apache License

/**
 * Save a persistent ID entry into the mongo database.
 *
 * @param entry entry to persist//from  w ww  .  j  av  a2  s.  c o m
 */
protected void savePersistentId(PersistentIdEntry entry) {
    try {
        DBCollection collection = db.getCollection(mongoCollection);
        BasicDBObject query = new BasicDBObject();
        query.put("localEntity", entry.getLocalEntityId());
        query.put("peerEntity", entry.getPeerEntityId());
        query.put("principalName", entry.getPrincipalName());
        query.put("localId", entry.getLocalId());
        query.put("persistentId", entry.getPersistentId());
        query.put("creationTime", entry.getCreationTime());
        query.put("lastVisitTime", entry.getLastVisitTime());

        collection.insert(query);

    } catch (MongoException e) {
        log.error("Failed to save persistent ID to the database", e);
    }
}

From source file:org.wso2.security.tools.util.DatabaseUtils.java

License:Open Source License

public void insertIntoDatabase(ArrayList<MethodReference> methodReferences) {

    // To connect to mongodb server
    MongoClient mongoClient = DatabaseUtils.getMongoClient();

    // Connecting to the databases
    DB db = mongoClient.getDB(Constants.DB_NAME);

    // Get the Collection with name Usages
    // Not necessarily this 'Collection' must exist in the DB.
    DBCollection usages = db.getCollection("Usages");

    for (MethodReference ref : methodReferences) {
        BasicDBObject obj = new BasicDBObject();
        obj.append("method_name", ref.getMethodName());
        obj.append("owner_class", ref.getParentClass());
        obj.append("usage_class", ref.getUsageClass());
        obj.append("usage_method", ref.getUsageMethod());
        obj.append("line_number", ref.getUsageLineNumber());
        usages.insert(obj);
    }/*from   w w w.j ava  2 s  .co m*/

}

From source file:org.zeus.HealthEnhancements.ProviderInfo.java

public boolean CreateProvider(String szUserName, String szPassword) {
    m_szUserName = szUserName;/*w ww  . j ava  2  s.  c om*/
    m_szHashUserPassword = szPassword;

    HashMap<String, ProviderInfo> mpProviders = GetAllProviders();

    if (mpProviders.containsKey(m_szUserName))
        return false; // provider already exists in the system

    DBCollection collection = Bootstrap.getEHRdbHandle().getCollection("ProviderInfo");

    collection.insert(new BasicDBObject("m_szUserName", m_szUserName)
            .append("m_szHashUserPassword", m_szHashUserPassword).append("m_szProviderType", m_szProviderType)
            .append("m_szFirstName", m_szFirstName).append("m_szLastName", m_szLastName)
            .append("m_szMiddleName", m_szMiddleName).append("m_szSocialSecurity", m_szSocialSecurity)
            .append("m_szLicenseNumber", m_szLicenseNumber).append("m_szPersonnelType", m_szPersonnelType)
            .append("m_szSpecialization", m_szSpecialization).append("m_szAffiliation", m_szAffiliation)
            .append("m_szAddress", m_szAddress).append("m_szPhoneNumber", m_szPhoneNumber)
            .append("m_szEmail", m_szEmail));

    LoadProviderProfile(szUserName, szPassword);

    return true;
}

From source file:others.Capped.java

License:Apache License

public static void main(String[] args) throws MongoException, UnknownHostException {

    MongoURI uri = new MongoURI("mongodb://10.11.0.52:27017/test");
    DB db = new Mongo(uri).getDB("test");
    DBObject foo = new BasicDBObject();
    foo.put("create", "capped1");
    foo.put("capped", true);
    foo.put("size", 100000000);
    DBObject dbobj = db.command(foo);//from   w w  w  .  j a  va 2 s.c o m
    DBCollection c = db.getCollection("capped1");

    DBObject obj = new BasicDBObject();
    Date begin = new Date();
    for (int i = 1; i <= 1000000; i++) {
        obj.removeField("x");
        obj.put("x", i);
        c.insert(obj);
    }
    Date end = new Date();
    System.out.println("One by one:" + ((end.getTime() - begin.getTime()) / 1000));

    DBObject foo2 = new BasicDBObject();
    foo.put("create", "capped2");
    foo.put("capped", true);
    foo.put("size", 100000000);
    DBObject dbobj2 = db.command(foo);
    DBCollection c2 = db.getCollection("capped2");

    begin = new Date();
    for (int i = 1; i <= 1000; i++) {
        List<DBObject> list = new ArrayList<DBObject>(1000);
        for (int j = 1; j <= 1000; j++) {
            DBObject dbo = new BasicDBObject();
            dbo.put("x", j + (i - 1) * 1000);
            list.add(dbo);
        }
        c2.insert(list);
    }
    end = new Date();
    System.out.println("Batch(per 1000):" + ((end.getTime() - begin.getTime()) / 1000));
}