Refine search
final CommandResult dbStatsResult = db.command("dbStats"); if (dbStatsResult.ok()) { final BasicDBObject extentFreeListMap = (BasicDBObject) dbStatsResult.get("extentFreeList"); final DatabaseStats.ExtentFreeList extentFreeList; if (extentFreeListMap == null) { final BasicDBObject dataFileVersionMap = (BasicDBObject) dbStatsResult.get("dataFileVersion"); final DatabaseStats.DataFileVersion dataFileVersion; if (dataFileVersionMap == null) { dbStatsResult.getString("db"), dbStatsResult.getLong("collections"), dbStatsResult.getLong("objects"), dbStatsResult.getDouble("avgObjSize"), dbStatsResult.getLong("dataSize"), dbStatsResult.getLong("storageSize"), dbStatsResult.getLong("numExtents"), dbStatsResult.getLong("indexes"), dbStatsResult.getLong("indexSize"), dbStatsResult.containsField("fileSize") ? dbStatsResult.getLong("fileSize") : null, dbStatsResult.containsField("nsSizeMB") ? dbStatsResult.getLong("nsSizeMB") : null, extentFreeList, dataFileVersion ); } else { LOG.debug("Couldn't retrieve MongoDB dbStats: {}", dbStatsResult.getErrorMessage()); dbStats = null; final CommandResult serverStatusResult = adminDb.command("serverStatus");
void process(final MappedClass mc, final Validation validation) { if (validation != null) { String collectionName = mc.getCollectionName(); CommandResult result = getDB() .command(new BasicDBObject("collMod", collectionName) .append("validator", parse(validation.value())) .append("validationLevel", validation.level().getValue()) .append("validationAction", validation.action().getValue()) ); if (!result.ok()) { if (result.getInt("code") == 26) { ValidationOptions options = new ValidationOptions() .validator(parse(validation.value())) .validationLevel(validation.level()) .validationAction(validation.action()); getDatabase().createCollection(collectionName, new CreateCollectionOptions().validationOptions(options)); } else { result.throwOnError(); } } } }
private static BuildInfo createBuildInfo(DB adminDb) { final BuildInfo buildInfo; final CommandResult buildInfoResult = adminDb.command("buildInfo"); if (buildInfoResult.ok()) { buildInfo = BuildInfo.create( buildInfoResult.getString("version"), buildInfoResult.getString("gitVersion"), buildInfoResult.getString("sysInfo"), buildInfoResult.getString("loaderFlags"), buildInfoResult.getString("compilerFlags"), buildInfoResult.getString("allocator"), (List<Integer>) buildInfoResult.get("versionArray"), buildInfoResult.getString("javascriptEngine"), buildInfoResult.getInt("bits"), buildInfoResult.getBoolean("debug"), buildInfoResult.getLong("maxBsonObjectSize") ); } else { LOG.debug("Couldn't retrieve MongoDB buildInfo: {}", buildInfoResult.getErrorMessage()); buildInfo = null; } return buildInfo; }
/** * Throws a {@code CommandFailureException} if the command failed. Otherwise, returns normally. * * @throws MongoException with the exception from the failed command * @see #ok() */ public void throwOnError() { if (!ok()) { throw createException(); } }
/** * Only calls DBCollection.count() when using vanilla MongoDB; otherwise gets estimate from collection.getStats() */ private String safeCount(DBCollection collection, Class<? extends Timestamp> type) { if (type.equals(Timestamp.BSON.class)) { return "" + collection.count(); // Vanilla MongoDB can quickly return precise count } CommandResult stats = collection.getStats(); return "~" + (!stats.containsField("count") ? 0l : stats.getLong("count")); }
final String ns = inputCollection.getFullName(); data = authDB.command(cmd); if (data.containsField("$err")) { throw new SplitFailedException("Error calculating splits: " + data); } else if (!data.get("ok").equals(1.0)) { ok = false; CommandResult stats = inputCollection.getStats(); if (stats.containsField("primary")) { DBCursor shards = inputCollection.getDB().getSisterDB("config") .getCollection("shards") .find(new BasicDBObject("_id", stats.getString("primary"))); try { if (shards.hasNext()) { DBObject shard = shards.next(); MongoClientURI shardHost = new MongoClientURIBuilder(inputURI) .host((String) shard.get("host")) .build(); MongoClient shardClient = null; if (!data.get("ok").equals(1.0)) { throw new SplitFailedException("Unable to calculate input splits: " + data.get("errmsg")); BasicDBList splitData = (BasicDBList) data.get("splitKeys");
DBCollection coll = db.getCollection(collection); DBObject docDbo = new BasicDBObject(doc); docDboList.add(docDbo); logger.debug("Execute 'insert' mongodb command. Doc '" + docDbo + "'."); WriteResult writeResult = coll.insert(docDboList, WriteConcern.SAFE); String errorMessage = writeResult.getLastError(WriteConcern.SAFE).getErrorMessage(); if (!StringUtils.isBlank(errorMessage)) { throw new MongoDaoException(statement, "Execute 'insert' mongodb command has exception. Cause: " + errorMessage); String newId = docDbo.get("_id").toString(); newIds.add(newId); logger.debug("Execute 'insert' mongodb command. ObjectId is '" + newId + "'.");
@Override public synchronized void createIndex(DBObject keys, DBObject options, DBEncoder encoder) throws MongoException { DBCollection indexColl = fongoDb.getCollection("system.indexes"); BasicDBObject rec = new BasicDBObject(); rec.append("v", 1); rec.append("key", keys); rec.append("ns", this.getDB().getName() + "." + this.getName()); if (options != null && !options.containsField("name")) { StringBuilder sb = new StringBuilder(); boolean firstLoop = true; for (String keyName : keys.keySet()) { if (!firstLoop) { sb.append("_"); sb.append(keyName).append("_").append(keys.get(keyName)); firstLoop = false; if (indexColl.findOne(rec) != null) { return; fongoDb.errorResult(11000, "E11000 duplicate key error index: " + getFullName() + "." + rec.get("name") + " dup key: { : " + notUnique + " }").throwOnError(); fongoDb.errorResult(me.getCode(), me.getMessage()).throwOnError(); indexColl.insert(rec);
public static AggregationOutput aggregate(PersistenceContext context, MetaClass metadata, DBObject firstObject, DBObject... aggrObjects) { long start = System.currentTimeMillis(); String msg = "success"; DBCollection dbCollection = context.getDBCollection(metadata); AggregationOutput output = null; try { output = dbCollection.aggregate(firstObject, aggrObjects); if (!output.getCommandResult().ok()) { throw new CmsDalException(DalErrCodeEnum.AGGREGATION_FAILED, output.getCommandResult() .getErrorMessage()); } } catch (Throwable t) { msg = t.getMessage(); handleMongoException(t); } finally { DBObject followingOjbect = new BasicDBObject(); followingOjbect.put("following aggreate operations: ", aggrObjects); logMongoAction(context, "aggregate", start, dbCollection, firstObject, followingOjbect, null, null, msg); } return output; }
public KvEntity create(DBCollection storage, DBObject value) { KvEntity entity = new KvEntity(); entity.version = 0; entity.value = value; entity.updated = null; entity.tx = null; DBObject record = new BasicDBObject(); record.put("version", entity.version); record.put("value", entity.value); record.put("updated", entity.updated); record.put("tx", entity.tx); storage.insert(record).getLastError().throwOnError(); entity.id = record.get("_id"); return entity; }
@Override public int delete(String statement, Object parameter) { logger.debug("Execute 'delete' mongodb command. Statement '" + statement + "'."); DeleteConfig config = (DeleteConfig) configuration.getConfig(statement); if (config == null) { throw new MongoDaoException(statement, "Delete statement id '" + statement + "' not found."); } String collection = config.getCollection(); NodeEntry query = config.getQuery(); DB db = factory.getDataSource().getDB(); DBCollection coll = db.getCollection(collection); Map<String, Object> q = (Map<String, Object>) query.executorNode(configuration, parameter); DBObject queryDbo = new BasicDBObject(q); logger.debug("Execute 'delete' mongodb command. Query '" + queryDbo + "'."); WriteResult writeResult = coll.remove(queryDbo, WriteConcern.SAFE); CommandResult commandResult = writeResult.getLastError(WriteConcern.SAFE); if (commandResult.getException() != null) { throw new MongoDaoException(statement, "Execute 'delete' mongodb command has exception. Cause: " + commandResult.getErrorMessage()); } return writeResult.getN(); }
@Override public int update(String statement, Object parameter) { logger.debug("Execute 'update' mongodb command. Statement '" + statement + "'."); UpdateConfig config = (UpdateConfig) configuration.getConfig(statement); if (config == null) { throw new MongoDaoException(statement, "Update statement id '" + statement + "' not found."); } String collection = config.getCollection(); NodeEntry query = config.getQuery(); NodeEntry action = config.getAction(); DB db = factory.getDataSource().getDB(); DBCollection coll = db.getCollection(collection); Map<String, Object> q = (Map<String, Object>) query.executorNode(configuration, parameter); Map<String, Object> a = (Map<String, Object>) action.executorNode(configuration, parameter); DBObject queryDbo = new BasicDBObject(q); logger.debug("Execute 'update' mongodb command. Query '" + queryDbo + "'."); DBObject actionDbo = (a == null) ? null : new BasicDBObject(a); logger.debug("Execute 'update' mongodb command. Action '" + actionDbo + "'."); WriteResult writeResult = coll.update(queryDbo, actionDbo, false, true, WriteConcern.SAFE); CommandResult commandResult = writeResult.getLastError(WriteConcern.SAFE); if (commandResult.getException() != null) { throw new MongoDaoException(statement, "Execute 'update' mongodb command has exception. Cause: " + commandResult.getErrorMessage()); } return writeResult.getN(); }
boolean authResult = dbRef.authenticate(username, password.toCharArray()); if (!authResult) { logger.error("Failed to authenticate user: " + username + " with password: " + password + ". Unable to write events."); DBCollection collection = dbRef.getCollection(collectionName); for (DBObject doc : docs) { if (logger.isDebugEnabled()) { .add(PK, doc.get(PK)).get(); BasicDBObjectBuilder doc_builder = BasicDBObjectBuilder.start(); if (doc.keySet().contains(OP_INC)) { doc_builder.add(OP_INC, doc.get(OP_INC)); if (doc.keySet().contains(OP_SET)) { CommandResult result = collection.update(query, doc, true, false, WriteConcern.SAFE).getLastError(); if (result.ok()) { String errorMessage = result.getErrorMessage(); if (errorMessage != null) { logger.error("can't upsert documents with error: {} ", errorMessage); logger.error("with exception", result.getException()); throw new MongoException(errorMessage);
public void delete(DBCollection storage, KvEntity entity) { DBObject query = new BasicDBObject(); query.put("_id", entity.id); query.put("version", entity.version); WriteResult result = storage.remove(query); result.getLastError().throwOnError(); if (result.getN()==0) throw new RuntimeException(); } }
public KvEntity update(DBCollection storage, KvEntity entity) { int version = (Integer)entity.version; DBObject query = new BasicDBObject(); query.put("_id", entity.id); query.put("version", version); DBObject record = new BasicDBObject(); record.put("version", version+1); record.put("value", entity.value); record.put("updated", entity.updated); record.put("tx", entity.tx); WriteResult result = storage.update(query, record); result.getLastError().throwOnError(); if (result.getN()==0) throw new RuntimeException(); entity.version = version+1; return entity; }
@Override public boolean delete(ObjectId id) { DBObject query = new BasicDBObject(); query.put("oid", id.toString()); return collection.remove(query).getLastError().ok(); }
@Override public boolean put(final RevObject object) { DBObject query = new BasicDBObject(); query.put("oid", object.getId().toString()); DBObject record = toDocument(object); return collection.update(query, record, true, false).getLastError().ok(); }
public static void update(DBCollection coll, DBObject query, DBObject data, boolean upsert, boolean multi){ // build the update command info BasicDBObject update = new BasicDBObject("q", query); update.append("u", data).append("upsert", upsert).append("multi", multi); // the command requires a list of operations BasicDBList updates = new BasicDBList(); updates.add(update); // create the command itself BasicDBObject updateCmd = new BasicDBObject("update", coll.getName()); updateCmd.append("updates", updates); // execute the command on the collections database DB configDb = coll.getDB(); CommandResult result = configDb.command(updateCmd); // convert any error to an exception and throw result.throwOnError(); }
@Override public Bounds bbox(DBCollection dbcol, MongoDataset data) { MapReduceCommand mr = new MapReduceCommand( dbcol, bboxMap, bboxReduce, null, OutputType.INLINE, new BasicDBObject()); BasicDBList list = (BasicDBList) dbcol.mapReduce(mr).getCommandResult().get("results"); DBObject bbox = (DBObject) ((DBObject) list.get(0)).get("value"); return new Bounds((Double)bbox.get("x1"), (Double)bbox.get("x2"), (Double)bbox.get("y1"), (Double)bbox.get("y2")); }
DBCollection coll = db.getCollection( uri.getCollection() ); final CommandResult stats = coll.getStats(); final boolean isSharded = stats.getBoolean( "sharded", false );