checkPermission(RestPermissions.METRICS_READHISTORY, metricName); BasicDBObject andQuery = new BasicDBObject(); obj.add(new BasicDBObject("name", metricName)); if (after != -1) { obj.add(new BasicDBObject("$gt", new BasicDBObject("$gt", new Date(after)))); andQuery.put("$and", obj); final DBCollection dbCollection = mongoConnection.getDatabase().getCollection("graylog2_metrics"); try(DBCursor cursor = dbCollection.find(andQuery).sort(new BasicDBObject("timestamp", 1))) { final Map<String, Object> metricsData = Maps.newHashMap(); metricsData.put("name", metricName); metricsData.put("values", values); while (cursor.hasNext()) { final DBObject value = cursor.next(); metricsData.put("node", value.get("node")); final MetricType metricType = MetricType.valueOf(((String) value.get("type")).toUpperCase(Locale.ENGLISH)); Map<String, Object> dataPoint = Maps.newHashMap(); values.add(dataPoint); dataPoint.put("timestamp", value.get("timestamp")); metricsData.put("type", metricType.toString().toLowerCase(Locale.ENGLISH));
private void addQueryToStream(final Operation operation, final Timestamp<?> currentTimestamp, final DBObject update, final String collection) throws InterruptedException { if (logger.isTraceEnabled()) { logger.trace("addQueryToStream - operation [{}], currentTimestamp [{}], update [{}]", operation, currentTimestamp, update); } if (collection == null) { for (String name : slurpedDb.getCollectionNames()) { DBCollection slurpedCollection = slurpedDb.getCollection(name); addQueryToStream(operation, currentTimestamp, update, name, slurpedCollection); } } else { DBCollection slurpedCollection = slurpedDb.getCollection(collection); addQueryToStream(operation, currentTimestamp, update, collection, slurpedCollection); } }
cr = mongoAdminDB.command(new BasicDBObject("addShard", command)); logger.info(cr.toString()); cr = mongoAdminDB.command(new BasicDBObject("listShards", 1)); logger.info(cr.toString()); cr = mongoAdminDB.command(new BasicDBObject("enableSharding", this.shardDatabase)); logger.info(cr.toString()); DB db = mongo.getDB(this.shardDatabase); db.getCollection(this.shardCollection).createIndex(this.shardKey); DBObject cmd = new BasicDBObject(); cmd.put("shardCollection", this.shardDatabase + "." + this.shardCollection); cmd.put("key", new BasicDBObject(this.shardKey, 1)); cr = mongoAdminDB.command(cmd); logger.info(cr.toString()); DBCursor cursor = mongo.getDB("config").getCollection("shards").find(); while (cursor.hasNext()) { DBObject item = cursor.next(); logger.info(item.toString());
/** * Executes a database command. This method constructs a simple DBObject using {@code command} as the field name and {@code true} as its * value, and calls {@link DB#command(DBObject, ReadPreference) } with the default read preference for the database. * * @param command command to execute * @return result of command from the database * @throws MongoException if the command failed * @mongodb.driver.manual tutorial/use-database-commands Commands */ public CommandResult command(final String command) { return command(new BasicDBObject(command, Boolean.TRUE), getReadPreference()); }
/** * Drops this database. Removes all data on disk. Use with caution. * * @throws MongoException if the operation failed * @mongodb.driver.manual reference/command/dropDatabase/ Drop Database */ public void dropDatabase() { try { getExecutor().execute(new DropDatabaseOperation(getName(), getWriteConcern()), getReadConcern()); } catch (MongoWriteConcernException e) { throw createWriteConcernException(e); } }
@Inject public IndexFailureServiceImpl(MongoConnection mongoConnection) { super(mongoConnection); // Make sure that the index failures collection is always created capped. final String collectionName = IndexFailureImpl.class.getAnnotation(CollectionName.class).value(); if (!mongoConnection.getDatabase().collectionExists(collectionName)) { final DBObject options = BasicDBObjectBuilder.start() .add("capped", true) .add("size", 52428800) // 50MB max size. .get(); final DBCollection collection = mongoConnection.getDatabase().createCollection(collectionName, options); collection.createIndex(new BasicDBObject("timestamp", 1)); collection.createIndex(new BasicDBObject("letter_id", 1)); } }
MongoClient mongoClient = new MongoClient(); DB db = mongoClient.getDB("test"); DBCollection coll = db.getCollection("testCollection"); BasicDBObject query = new BasicDBObject("_id", "51a29f6413dc992c24e0283e"); DBCursor cursor = coll.find(query); try { while(cursor.hasNext()) { System.out.println(cursor.next()); } } finally { cursor.close(); }
private Timestamp<?> getCurrentOplogTimestamp(MongoClient shardClient) { DBCollection oplogCollection = shardClient .getDB(MongoDBRiver.MONGODB_LOCAL_DATABASE) .getCollection(MongoDBRiver.OPLOG_COLLECTION); try (DBCursor cursor = oplogCollection.find().sort(new BasicDBObject("$natural", -1)).limit(1)) { return Timestamp.on(cursor.next()); } }
.connectTimeout(10) .build(); MongoClient mongo = new MongoClient(new ServerAddress(mongoConfigList.get(0).net() .getServerAddress().getHostName(), mongoConfigList.get(0).net() .getPort()), mo); DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); .command(new BasicDBObject("isMaster", 1)); logger.info("isMaster: {}", cr); logger.info(replicaSetSetting.toString()); cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting)); logger.info("replSetInitiate: {}", cr); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: {}", cr); logger.info("Waiting for 3 seconds..."); Thread.sleep(1000); cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1)); logger.info("replSetGetStatus: {}", cr); mongo.close(); mongo = null;
@Inject public DBCacheService(MongoConnection mongoConnection, MongoJackObjectMapperProvider mapper, ClusterEventBus clusterEventBus) { this.db = JacksonDBCollection.wrap(mongoConnection.getDatabase().getCollection("lut_caches"), CacheDto.class, ObjectId.class, mapper.get()); this.clusterEventBus = clusterEventBus; db.createIndex(new BasicDBObject("name", 1), new BasicDBObject("unique", true)); }
@Test @SuppressWarnings("deprecation") public void testCommentsShowUpInLogsOld() { getDs().save(asList(new Pic("pic1"), new Pic("pic2"), new Pic("pic3"), new Pic("pic4"))); getDb().command(new BasicDBObject("profile", 2)); String expectedComment = "test comment"; toList(getDs().find(Pic.class).comment(expectedComment).find()); DBCollection profileCollection = getDb().getCollection("system.profile"); assertNotEquals(0, profileCollection.count()); DBObject profileRecord = profileCollection.findOne(new BasicDBObject("op", "query") .append("ns", getDs().getCollection(Pic.class).getFullName())); assertEquals(profileRecord.toString(), expectedComment, getCommentFromProfileRecord(profileRecord)); turnOffProfilingAndDropProfileCollection(); }
@Test public void testRecursiveReference() { final DBCollection stuff = getDb().getCollection("stuff"); stuff.save(parentDbObj); stuff.save(childDbObj); stuff.findOne(new BasicDBObject("_id", parentDbObj.get("_id"))), new DefaultEntityCache()); final RecursiveChild childLoaded = getMorphia().fromDBObject(getDs(), RecursiveChild.class, stuff.findOne(new BasicDBObject("_id", childDbObj.get("_id"))), new DefaultEntityCache()); stuff.findOne(new BasicDBObject("_id", parentDbObj.get("_id"))), new DefaultEntityCache()); final RecursiveChild finalChildLoaded = getMorphia().fromDBObject(getDs(), RecursiveChild.class,
/** {@inheritDoc} */ @Override public void createSchema() { if (!mongoClient.getDB(dbName).collectionExists(collectionName)) { BasicDBObject options = new BasicDBObject(); options.put("size", 10000); mongoClient.getDB(dbName).createCollection(collectionName, options); } propertiesCollection = mongoClient.getDB(dbName).getCollection(collectionName); }
final MongoClient mongoClient = new MongoClient(); final DB db = mongoClient.getDB("DB_NAME"); final DBCollection collection = db.getCollection("item"); final DBObject groupIdFields = new BasicDBObject("_id", "$name"); groupIdFields.put("count", new BasicDBObject("$sum", 1)); final DBObject group = new BasicDBObject("$group", groupIdFields); final DBObject projectFields = new BasicDBObject("_id", 0); projectFields.put("name", "$_id"); projectFields.put("count", 1); final DBObject project = new BasicDBObject("$project", projectFields); final AggregationOutput aggregate = collection.aggregate(group, project);
public MongoSchemaDBStore(MongoClientURI uri) throws IOException { client = new MongoClient(uri); String databaseName = uri.getDatabase(); if (databaseName == null) { databaseName = DEFAULT_databaseName; } DB database = client.getDB(databaseName); String collectionName = uri.getCollection(); if (collectionName == null) { collectionName = DEFAULT_collectionName; } collection = database.getCollection(collectionName); collection.createIndex( new BasicDBObject(FeatureTypeDBObject.KEY_typeName, 1), new BasicDBObject("unique", true)); }
Mongo m = new Mongo("localhost", 27017); DB db = m.getDB("test"); DBCollection myColl = db.getCollection("myCollection"); BasicDBObject docToInsert = new BasicDBObject("resourceID", "3"); docToInsert.put("resourceName", "Foo Test3"); BasicDBObject updateQuery = new BasicDBObject("_id", "1"); updateQuery.put("itemList.itemID", "1"); BasicDBObject updateCommand = new BasicDBObject("$push", new BasicDBObject("itemList.$.resources", docToInsert)); myColl.update(updateQuery, updateCommand); System.out.println(myColl.findOne().toString());
private DBCursor curs; public Nextstud() { Mongo s = new Mongo(); DB db = s.getDB( "omrs1" ); DBCollection coll = db.getCollection("Student") ; curs = coll.find(); if(curs.hasNext()) { DBObject o = curs.next(); String fname = (String) o.get("Firstname") ; String lname = (String) o.get("Lastname") ; String sid = (String) o.get("StudentID") ; String prg = (String) o.get("Programme") ; String lvl = (String) o.get("Level") ;
private List<Shard> getShards(boolean isMongos) { List<Shard> shards = new ArrayList<>(); if (isMongos) { try (DBCursor cursor = getConfigDb().getCollection("shards").find()) { while (cursor.hasNext()) { DBObject item = cursor.next(); List<ServerAddress> shardServers = getServerAddressForReplica(item); if (shardServers != null) { String shardName = item.get(MongoDBRiver.MONGODB_ID_FIELD).toString(); MongoClient shardClient = mongoClientService.getMongoShardClient(definition, shardServers); ensureIsReplicaSet(shardClient); Timestamp<?> latestOplogTimestamp = getCurrentOplogTimestamp(shardClient); shards.add(new Shard(shardName, shardServers, latestOplogTimestamp)); } } } return shards; } else { ensureIsReplicaSet(clusterClient); List<ServerAddress> servers = clusterClient.getServerAddressList(); Timestamp<?> latestOplogTimestamp = getCurrentOplogTimestamp(clusterClient); shards.add(new Shard("unsharded", servers, latestOplogTimestamp)); return shards; } }
@Override public void connect() { try { mongoClient = new MongoClient(hostName); db = mongoClient.getDB(dataBase); if (userName != null && passWord != null) { db.authenticate(userName, passWord.toCharArray()); } } catch (UnknownHostException ex) { throw new RuntimeException("creating mongodb client", ex); } }
public OplogSlurper(MongoDBRiver river, Timestamp<?> timestamp, MongoClient mongoClusterClient, MongoClient mongoShardClient) { super(river); this.river = river; this.timestamp = timestamp; this.definition = river.definition; this.context = river.context; this.esClient = river.esClient; this.mongoClusterClient = mongoClusterClient; this.mongoShardClient = mongoShardClient; this.findKeys = new BasicDBObject(); this.gridfsOplogNamespace = definition.getMongoOplogNamespace() + MongoDBRiver.GRIDFS_FILES_SUFFIX; this.cmdOplogNamespace = definition.getMongoDb() + "." + MongoDBRiver.OPLOG_NAMESPACE_COMMAND; if (definition.getExcludeFields() != null) { for (String key : definition.getExcludeFields()) { findKeys.put(key, 0); } } else if (definition.getIncludeFields() != null) { for (String key : definition.getIncludeFields()) { findKeys.put(key, 1); } } this.oplogDb = mongoShardClient.getDB(MongoDBRiver.MONGODB_LOCAL_DATABASE); this.oplogCollection = oplogDb.getCollection(MongoDBRiver.OPLOG_COLLECTION); this.oplogRefsCollection = oplogDb.getCollection(MongoDBRiver.OPLOG_REFS_COLLECTION); this.slurpedDb = mongoShardClient.getDB(definition.getMongoDb()); }