private static MongoClient newMongoClient(MongoClientURI clientUri) { return new MongoClient(clientUri); }
private void createTableMetadata(SchemaTableName schemaTableName, List<MongoColumnHandle> columns) throws TableNotFoundException { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); Document metadata = new Document(TABLE_NAME_KEY, tableName); ArrayList<Document> fields = new ArrayList<>(); if (!columns.stream().anyMatch(c -> c.getName().equals("_id"))) { fields.add(new MongoColumnHandle("_id", OBJECT_ID, true).getDocument()); } fields.addAll(columns.stream() .map(MongoColumnHandle::getDocument) .collect(toList())); metadata.append(FIELDS_KEY, fields); MongoCollection<Document> schema = db.getCollection(schemaCollection); schema.createIndex(new Document(TABLE_NAME_KEY, 1), new IndexOptions().unique(true)); schema.insertOne(metadata); }
public void shutdown() { client.close(); }
public MongoConnectionForTests(MongoClient mongoClient, String dbName) { this.mongoClient = requireNonNull(mongoClient); this.db = mongoClient.getDB(dbName); this.mongoDatabase = mongoClient.getDatabase(dbName); }
/** * The MongoDbClient constructor. * @param url The Mongo server url * @param collectionName The Mongo collection to read/write data */ public MongoDbClient(String url, String collectionName) { //Creates a MongoURI from the given string. MongoClientURI uri = new MongoClientURI(url); //Creates a MongoClient described by a URI. this.client = new MongoClient(uri); //Gets a Database. MongoDatabase db = client.getDatabase(uri.getDatabase()); //Gets a collection. this.collection = db.getCollection(collectionName); }
private DatastoreImpl(final Morphia morphia, final Mapper mapper, final MongoClient mongoClient, final MongoDatabase database) { this.morphia = morphia; this.mapper = mapper; this.mongoClient = mongoClient; this.database = database.withCodecRegistry(CodecRegistries.fromRegistries( mongoClient.getMongoClientOptions().getCodecRegistry(), MongoClientSettings.getDefaultCodecRegistry())); this.db = mongoClient.getDB(database.getName()); this.defConcern = mongoClient.getWriteConcern(); this.indexHelper = new IndexHelper(mapper, database); }
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()); } }
MongoClient mongo = new MongoClient( "localhost" , 27017 ); DB db = mongo.getDB(dbName); DBCollection collection = db.getCollection(collectionName); BasicDBObject whereQuery = new BasicDBObject(); whereQuery.put("movie_id", id); DBObject document = collection.findOne(whereQuery); BasicDBList list = (BasicDBList) document.get("genre"); List<String> res = new ArrayList<String>(); for(Object el: list) { res.add((String) el); }
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);
@Test public void simpleMongoDbTest() { MongoClient mongoClient = new MongoClient(mongo.getContainerIpAddress(), mongo.getMappedPort(MONGO_PORT)); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("testCollection"); Document doc = new Document("name", "foo") .append("value", 1); collection.insertOne(doc); Document doc2 = collection.find(new Document("name", "foo")).first(); assertEquals("A record can be inserted into and retrieved from MongoDB", 1, doc2.get("value")); }
/** * No authentication test. * */ // @Test public void noAuthenticationTest() { try { _PU = "mongoTest"; String dbname = "KunderaAuthTests"; MongoClient m = new MongoClient(new ServerAddress("localhost", 27017)); DB db = m.getDB(dbname); Assert.assertNotNull(db.getCollectionNames()); emf = Persistence.createEntityManagerFactory(_PU); Assert.assertNotNull(emf); EntityManager em = emf.createEntityManager(); Assert.assertNotNull(em); } catch (Exception e) { Assert.fail(e.getMessage()); } }
.connectTimeout(10) .build(); try (MongoClient mongo = new MongoClient( new ServerAddress(this.config.net().getServerAddress() .getHostName(), this.config.net().getPort()), options)) { DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME); 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); DBCursor cursor = mongo.getDB("config").getCollection("shards").find(); while (cursor.hasNext()) { DBObject item = 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); mongo.close(); mongo = null;
private List<Document> guessTableFields(SchemaTableName schemaTableName) { String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); MongoDatabase db = client.getDatabase(schemaName); Document doc = db.getCollection(tableName).find().first(); if (doc == null) { // no records at the collection return ImmutableList.of(); } ImmutableList.Builder<Document> builder = ImmutableList.builder(); for (String key : doc.keySet()) { Object value = doc.get(key); Optional<TypeSignature> fieldType = guessFieldType(value); if (fieldType.isPresent()) { Document metadata = new Document(); metadata.append(FIELDS_NAME_KEY, key); metadata.append(FIELDS_TYPE_KEY, fieldType.get().toString()); metadata.append(FIELDS_HIDDEN_KEY, key.equals("_id") && fieldType.get().equals(OBJECT_ID.getTypeSignature())); builder.add(metadata); } else { log.debug("Unable to guess field type from %s : %s", value == null ? "null" : value.getClass().getName(), value); } } return builder.build(); }
MongoClient mongoClient = new MongoClient("SERVER", 27017); DB db = mongoClient.getDB("DB_NAME"); DBCollection coll1 = db.getCollection("COLLECTION_NAME"); DBObject eleMatch = new BasicDBObject(); eleMatch.put("url", "www.pqr.com"); eleMatch.put("type", new BasicDBObject("$lte", 50)); BasicDBObject up = new BasicDBObject(); up.put("$elemMatch", eleMatch); BasicDBList basicDBList = new BasicDBList(); basicDBList.add(up); DBObject query = new BasicDBObject("Data", new BasicDBObject(" $all", basicDBList)); coll1.find(query);
MongoClient mongo = new MongoClient("localhost", 27017); DB db = (DB) mongo.getDB("testDB"); DBCollection collection = db.getCollection("collection"); DBObject query = new BasicDBObject("_id", "10-100-5675234"); DBObject update = new BasicDBObject(); update.put("$unset", new BasicDBObject("userId","")); WriteResult result = collection.update(query, update); mongo.close();
private Set<String> getTableMetadataNames(String schemaName) throws TableNotFoundException { MongoDatabase db = client.getDatabase(schemaName); MongoCursor<Document> cursor = db.getCollection(schemaCollection) .find().projection(new Document(TABLE_NAME_KEY, true)).iterator(); HashSet<String> names = new HashSet<>(); while (cursor.hasNext()) { names.add((cursor.next()).getString(TABLE_NAME_KEY)); } return names; }
public static Object getNextSequence(String name) throws Exception{ MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); // Now connect to your databases DB db = mongoClient.getDB("demo"); DBCollection collection = db.getCollection("counters"); BasicDBObject find = new BasicDBObject(); find.put("_id", name); BasicDBObject update = new BasicDBObject(); update.put("$inc", new BasicDBObject("seq", 1)); DBObject obj = collection.findAndModify(find, update); return obj.get("seq");
/** * Add field use_raw_configuration_schema to endpointProfile that used to support devices using * SDK version 0.9.0 */ public void transform() { //mongo MongoClient client = new MongoClient(host); MongoDatabase database = client.getDatabase(dbName); MongoCollection<Document> endpointProfile = database.getCollection("endpoint_profile"); endpointProfile.updateMany(new Document(), eq("$set", eq("use_raw_schema", false))); //cassandra Cluster cluster = Cluster.builder().addContactPoint(host).build(); Session session = cluster.connect(dbName); session.execute("ALTER TABLE ep_profile ADD use_raw_schema boolean"); session.close(); cluster.close(); } }
public Mongo getMongo() throws UnknownHostException, MongoException { return new MongoClient(new ServerAddress(mongosProcess.getConfig().net() .getServerAddress(), mongosProcess.getConfig().net().getPort())); }