List of usage examples for com.mongodb CommandResult get
public Object get(final String key)
From source file:com.jaspersoft.mongodb.query.MongoDbQueryWrapper.java
License:Open Source License
public static void main(String[] args) { MongoDbConnection c = null;/* ww w. jav a 2s. c om*/ ReportTest reports = new ReportTest(); try { c = new MongoDbConnection("mongodb://localhost:27017/test", null, null); reports.test(); Object cmd = JSON.parse("{\n" + " aggregate : \"accounts\",\n" + " pipeline : [\n" + " {\n" + " $project : {\n" + " billing_address_street : 1,\n" + " billing_address_country : 1\n" + " }\n" + " }\n" + " ]\n" + " }"); CommandResult result = c.getMongoDatabase().command((DBObject) cmd); System.out.println(result.keySet()); System.out.println(result.get("ok") + " - " + result.ok()); System.out.println(result.get("result").getClass().getName()); } catch (Exception e) { logger.error(e); } finally { if (c != null) { c.close(); } } }
From source file:com.ninjas.movietime.health.MongoDbHealth.java
License:MIT License
@Override public Health health() { try {//from w ww. jav a 2s . c o m Preconditions.checkNotNull(mongoTemplate, "mongoTemplate is null"); DBObject ping = new BasicDBObject("ping", "1"); final CommandResult pingCommandResult = mongoTemplate.getDb().command(ping); pingCommandResult.throwOnError(); //ping worked, now getting version DBObject serverStatus = new BasicDBObject("serverStatus", "1"); final CommandResult serverStatusCommandResult = mongoTemplate.getDb().command(serverStatus); serverStatusCommandResult.throwOnError(); final String server = pingCommandResult.getServerUsed().toString(); final String version = serverStatusCommandResult.get("version").toString(); Preconditions.checkNotNull(server, "Mongo DB Server address is null"); Preconditions.checkNotNull(version, "Mongo DB version is null"); return Health.up().withDetail("database", "mongodb").withDetail("server", server) .withDetail("version", version).build(); } catch (Exception ex) { return Health.down(ex).build(); } }
From source file:com.redhat.lightblue.mongo.crud.MongoCRUDController.java
License:Open Source License
@Override public CRUDHealth checkHealth() { boolean isHealthy = true; Collection<MongoConfiguration> configs = dbResolver.getConfigurations(); Map<String, Object> healthDetails = new LinkedHashMap<>(); DBObject ping = new BasicDBObject("ping", 1); DB db = null;// w w w . j a v a2 s .co m for (MongoConfiguration config : configs) { boolean isDbHealthy = true; Map<String, Object> dbDetails = new LinkedHashMap<>(); try { db = dbResolver.get(new MongoDataStore(config.getDatabase(), null, null)); CommandResult result = db.command(ping); if (!result.get("ok").equals(1.0)) { isDbHealthy = false; isHealthy = false; } } catch (Exception e) { isDbHealthy = false; isHealthy = false; dbDetails.put("exception", e); } dbDetails.put("isHealthy", isDbHealthy); dbDetails.putAll(getMongoConfigDetails(config)); healthDetails.put(config.getDatabase(), dbDetails); } return new CRUDHealth(isHealthy, healthDetails); }
From source file:com.skymobi.monitor.model.Chart.java
License:Open Source License
public List findData() { logger.debug("find stats by {}", query); CommandResult result = null;//mongoDb.runCmd(query); logger.debug("stats mongo result {}", result); Object data = result.get("retval"); return (List) data; }
From source file:com.stratio.connector.mongodb.core.engine.metadata.DiscoverMetadataUtils.java
License:Apache License
/** * Discover the existing fields stored in the collection. * * @param collection/* w w w .j a va 2s . c o m*/ * the collection * @return the list of fields including the _id */ public static List<String> discoverField(DBCollection collection) { String map = "function() { for (var field in this) { emit(field, null); }}"; String reduce = "function(field, stuff) { return null; }"; MapReduceCommand mapReduceCommand = new MapReduceCommand(collection, map, reduce, null, OutputType.INLINE, null); DBObject getFieldsCommand = mapReduceCommand.toDBObject(); CommandResult command = collection.getDB().command(getFieldsCommand); BasicDBList results = (BasicDBList) command.get("results"); Set<String> fields = new HashSet<>(); if (results != null) { for (Object object : results) { DBObject bson = (DBObject) object; fields.add((String) bson.get("_id")); } } return new ArrayList<String>(fields); }
From source file:com.stratio.connector.mongodb.core.engine.metadata.DiscoverMetadataUtils.java
License:Apache License
/** * Discover the existing fields stored in the collection and their data types. * * @param collection/*from w w w .java 2 s.co m*/ * the collection * @return the list of fields including the _id */ public static HashMap<String, String> discoverFieldsWithType(DBCollection collection, String sample_probability) { String map = "function() { if(Math.random() <= sample_number) {for (var key in this) {var type = typeof(this[key]); if(type == \"object\"){type = \"string\";};emit(key, type);}} } "; String reduce = "function(key, values) { var result = \"\"; for (var i = 0; i < values.length; i++){ var v = values[i];if(v == \"string\"){result = \"string\"; break;} if(v == \"number\"){result = \"number\"} if(v == \"boolean\" && result == \"number\"){result = \"string\"; break;}if(v == \"number\" && result == \"boolean\"){result = \"string\"; break;} if(v==\"boolean\"){result = \"boolean\"}};return result; }"; MapReduceCommand mapReduceCommand = new MapReduceCommand(collection, map, reduce, null, OutputType.INLINE, null); HashMap<String, Object> scope = new HashMap<>(); // connection scope.put("sample_number", sample_probability); mapReduceCommand.setScope(scope); DBObject getFieldsCommand = mapReduceCommand.toDBObject(); CommandResult command = collection.getDB().command(getFieldsCommand); BasicDBList results = (BasicDBList) command.get("results"); HashMap<String, String> fields = new HashMap<>(); if (results != null) { for (Object object : results) { DBObject bson = (DBObject) object; String nameField = (String) bson.get("_id"); String type = (String) bson.get("value"); fields.put(nameField, type); } } return fields; }
From source file:com.zjy.mongo.splitter.StandaloneMongoSplitter.java
License:Apache License
@Override public List<InputSplit> calculateSplits() throws SplitFailedException { final DBObject splitKey = MongoConfigUtil.getInputSplitKey(getConfiguration()); final DBObject splitKeyMax = MongoConfigUtil.getMaxSplitKey(getConfiguration()); final DBObject splitKeyMin = MongoConfigUtil.getMinSplitKey(getConfiguration()); final int splitSize = MongoConfigUtil.getSplitSize(getConfiguration()); final MongoClientURI inputURI; DBCollection inputCollection = null; final ArrayList<InputSplit> returnVal; try {/*from w w w . j a va 2 s .c o m*/ inputURI = MongoConfigUtil.getInputURI(getConfiguration()); MongoClientURI authURI = MongoConfigUtil.getAuthURI(getConfiguration()); if (authURI != null) { inputCollection = MongoConfigUtil.getCollectionWithAuth(inputURI, authURI); } else { inputCollection = MongoConfigUtil.getCollection(inputURI); } returnVal = new ArrayList<InputSplit>(); final String ns = inputCollection.getFullName(); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Running splitVector on namespace: %s.%s; hosts: %s", inputURI.getDatabase(), inputURI.getCollection(), inputURI.getHosts())); } final DBObject cmd = BasicDBObjectBuilder.start("splitVector", ns).add("keyPattern", splitKey) .add("min", splitKeyMin).add("max", splitKeyMax) // force:True is misbehaving it seems .add("force", false).add("maxChunkSize", splitSize).get(); CommandResult data; boolean ok = true; try { data = inputCollection.getDB().getSisterDB(inputURI.getDatabase()).command(cmd, ReadPreference.primary()); } catch (final MongoException e) { // 2.0 servers throw exceptions rather than info in a CommandResult data = null; LOG.info(e.getMessage(), e); if (e.getMessage().contains("unrecognized command: splitVector")) { ok = false; } else { throw e; } } if (data != null) { if (data.containsField("$err")) { throw new SplitFailedException("Error calculating splits: " + data); } else if (!data.get("ok").equals(1.0)) { ok = false; } } if (!ok) { final CommandResult stats = inputCollection.getStats(); if (stats.containsField("primary")) { final DBCursor shards = inputCollection.getDB().getSisterDB("config").getCollection("shards") .find(new BasicDBObject("_id", stats.getString("primary"))); try { if (shards.hasNext()) { final DBObject shard = shards.next(); final String host = ((String) shard.get("host")).replace(shard.get("_id") + "/", ""); final MongoClientURI shardHost; if (authURI != null) { shardHost = new MongoClientURIBuilder(authURI).host(host).build(); } else { shardHost = new MongoClientURIBuilder(inputURI).host(host).build(); } MongoClient shardClient = null; try { shardClient = new MongoClient(shardHost); data = shardClient.getDB(shardHost.getDatabase()).command(cmd, ReadPreference.primary()); } catch (final Exception e) { LOG.error(e.getMessage(), e); } finally { if (shardClient != null) { shardClient.close(); } } } } finally { shards.close(); } } if (data != null && !data.get("ok").equals(1.0)) { throw new SplitFailedException("Unable to calculate input splits: " + data.get("errmsg")); } } // Comes in a format where "min" and "max" are implicit // and each entry is just a boundary key; not ranged final BasicDBList splitData = (BasicDBList) data.get("splitKeys"); if (splitData.size() == 0) { LOG.warn( "WARNING: No Input Splits were calculated by the split code. Proceeding with a *single* split. Data may be too" + " small, try lowering 'mongo.input.split_size' if this is undesirable."); } BasicDBObject lastKey = null; // Lower boundary of the first min split // If splitKeyMin was given, use it as first boundary. if (!splitKeyMin.toMap().isEmpty()) { lastKey = new BasicDBObject(splitKeyMin.toMap()); } for (final Object aSplitData : splitData) { final BasicDBObject currentKey = (BasicDBObject) aSplitData; returnVal.add(createSplitFromBounds(lastKey, currentKey)); lastKey = currentKey; } BasicDBObject maxKey = null; // If splitKeyMax was given, use it as last boundary. if (!splitKeyMax.toMap().isEmpty()) { maxKey = new BasicDBObject(splitKeyMax.toMap()); } // Last max split final MongoInputSplit lastSplit = createSplitFromBounds(lastKey, maxKey); returnVal.add(lastSplit); } finally { if (inputCollection != null) { MongoConfigUtil.close(inputCollection.getDB().getMongo()); } } return returnVal; }
From source file:de.fhg.igd.mongomvcc.impl.MongoDBVDatabase.java
License:Open Source License
/** * Obtains build information from the database instance. If any value is * not available, this method will return <code>null</code>. * @param mongo the database//from www. j ava2s .c om * @return the build information or <code>null</code> */ private static BuildInfo initBuildInfo(Mongo mongo) { DB db = mongo.getDB("admin"); if (db == null) { return null; } CommandResult cr = db.command("buildInfo"); String version = (String) cr.get("version"); if (version == null) { return null; } String[] vss = version.split("\\."); if (vss.length <= 2) { return null; } Integer maxBsonObjectSize = (Integer) cr.get("maxBsonObjectSize"); if (maxBsonObjectSize == null) { maxBsonObjectSize = Integer.valueOf(0); } try { return new BuildInfo(Integer.parseInt(vss[0]), Integer.parseInt(vss[1]), Integer.parseInt(vss[2]), maxBsonObjectSize); } catch (NumberFormatException e) { return null; } }
From source file:de.flapdoodle.mongoom.datastore.Errors.java
License:Apache License
public static void checkError(DB db, Operation operation) { CommandResult lastError = db.getLastError(); if (lastError.get("err") != null) { _logger.severe(lastError.get("err").toString()); // throw lastError.getException(); throw new ObjectMapperException(lastError.get("err").toString()); }// ww w . ja v a 2 s . c o m switch (operation) { case Update: if (lastError.getInt("updatedExisting", 0) == 0) { throw new UpdateFailedException(); } break; case Delete: if (lastError.getInt("n", 0) == 0) { throw new UpdateFailedException(); } break; } }
From source file:eu.eubrazilcc.lvl.storage.mongodb.MongoDBConnector.java
License:EUPL
/** * Returns the objects in the collection that are within the specified distance (in meters) * from the center point specified by the coordinates (in WGS84). The objects are sorted * from nearest to farthest./* w ww . jav a 2 s . c om*/ * @param collection - collection whose objects are counted * @param longitude - longitude in WGS84 coordinate reference system (CRS) * @param latitude - latitude in WGS84 coordinate reference system (CRS) * @param maxDistance - limits the results to those objects that fall within the specified * distance (in meters) from the center point * @return the objects that are within the specified distance from the center point, sorted * from nearest to farthest */ public BasicDBList geoNear(final String collection, final double longitude, final double latitude, final double maxDistance) { checkArgument(isNotBlank(collection), "Uninitialized or invalid collection"); final DB db = client().getDB(CONFIG_MANAGER.getDbName()); final BasicDBObject query = new BasicDBObject("geoNear", collection) .append("near", new BasicDBObject("type", "Point").append("coordinates", new double[] { longitude, latitude })) .append("maxDistance", maxDistance).append("spherical", true).append("uniqueDocs", true) .append("num", Integer.MAX_VALUE); LOGGER.trace("geoNear query: " + JSON.serialize(query)); final CommandResult cmdResult = db.command(query); checkState(cmdResult.ok(), "geoNear search failed"); return (BasicDBList) cmdResult.get("results"); }