Search in sources :

Example 1 with MongoClient

use of com.mongodb.MongoClient in project cas by apereo.

the class MongoDbCloudConfigBootstrapConfiguration method mongo.

@Override
public Mongo mongo() throws Exception {
    final MongoCredential credential = MongoCredential.createCredential(mongoClientUri().getUsername(), getDatabaseName(), mongoClientUri().getPassword());
    final String hostUri = mongoClientUri().getHosts().get(0);
    final String[] host = hostUri.split(":");
    return new MongoClient(new ServerAddress(host[0], host.length > 1 ? Integer.parseInt(host[1]) : DEFAULT_PORT), Collections.singletonList(credential), mongoClientOptions());
}
Also used : MongoClient(com.mongodb.MongoClient) MongoCredential(com.mongodb.MongoCredential) ServerAddress(com.mongodb.ServerAddress)

Example 2 with MongoClient

use of com.mongodb.MongoClient in project morphia by mongodb.

the class TestBase method setUp.

@Before
public void setUp() {
    final MongoClient mongoClient;
    try {
        mongoClient = new MongoClient();
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    mongoClient.dropDatabase("morphia_test");
    morphia = new Morphia();
    this.db = mongoClient.getDB("morphia_test");
    this.ds = this.morphia.createDatastore(mongoClient, this.db.getName());
}
Also used : MongoClient(com.mongodb.MongoClient) Morphia(org.mongodb.morphia.Morphia) Before(org.junit.Before)

Example 3 with MongoClient

use of com.mongodb.MongoClient in project morphia by mongodb.

the class Employee method main.

public static void main(final String[] args) throws UnknownHostException {
    final Morphia morphia = new Morphia();
    // tell morphia where to find your classes
    // can be called multiple times with different packages or classes
    morphia.mapPackage("org.mongodb.morphia.example");
    // create the Datastore connecting to the database running on the default port on the local host
    final Datastore datastore = morphia.createDatastore(new MongoClient(), "morphia_example");
    datastore.getDB().dropDatabase();
    datastore.ensureIndexes();
    final Employee elmer = new Employee("Elmer Fudd", 50000.0);
    datastore.save(elmer);
    final Employee daffy = new Employee("Daffy Duck", 40000.0);
    datastore.save(daffy);
    final Employee pepe = new Employee("Pepé Le Pew", 25000.0);
    datastore.save(pepe);
    elmer.getDirectReports().add(daffy);
    elmer.getDirectReports().add(pepe);
    datastore.save(elmer);
    Query<Employee> query = datastore.find(Employee.class);
    final List<Employee> employees = query.asList();
    Assert.assertEquals(3, employees.size());
    List<Employee> underpaid = datastore.find(Employee.class).filter("salary <=", 30000).asList();
    Assert.assertEquals(1, underpaid.size());
    underpaid = datastore.find(Employee.class).field("salary").lessThanOrEq(30000).asList();
    Assert.assertEquals(1, underpaid.size());
    final Query<Employee> underPaidQuery = datastore.find(Employee.class).filter("salary <=", 30000);
    final UpdateOperations<Employee> updateOperations = datastore.createUpdateOperations(Employee.class).inc("salary", 10000);
    final UpdateResults results = datastore.update(underPaidQuery, updateOperations);
    Assert.assertEquals(1, results.getUpdatedCount());
    final Query<Employee> overPaidQuery = datastore.find(Employee.class).filter("salary >", 100000);
    datastore.delete(overPaidQuery);
}
Also used : MongoClient(com.mongodb.MongoClient) Morphia(org.mongodb.morphia.Morphia) Datastore(org.mongodb.morphia.Datastore) UpdateResults(org.mongodb.morphia.query.UpdateResults)

Example 4 with MongoClient

use of com.mongodb.MongoClient in project openhab1-addons by openhab.

the class MongoDBPersistenceService method connectToDatabase.

/**
     * Connects to the database
     */
private void connectToDatabase() {
    try {
        logger.debug("Connect MongoDB");
        this.cl = new MongoClient(new MongoClientURI(this.url));
        mongoCollection = cl.getDB(this.db).getCollection(this.collection);
        BasicDBObject idx = new BasicDBObject();
        idx.append(FIELD_TIMESTAMP, 1).append(FIELD_ITEM, 1);
        this.mongoCollection.createIndex(idx);
        logger.debug("Connect MongoDB ... done");
    } catch (Exception e) {
        logger.error("Failed to connect to database {}", this.url);
        throw new RuntimeException("Cannot connect to database", e);
    }
}
Also used : MongoClient(com.mongodb.MongoClient) BasicDBObject(com.mongodb.BasicDBObject) MongoClientURI(com.mongodb.MongoClientURI) ItemNotFoundException(org.openhab.core.items.ItemNotFoundException)

Example 5 with MongoClient

use of com.mongodb.MongoClient in project mongo-java-driver by mongodb.

the class QuickTourAdmin method main.

/**
     * Run this main method to see the output of this quick example.
     *
     * @param args takes an optional single argument for the connection string
     */
public static void main(final String[] args) {
    MongoClient mongoClient;
    if (args.length == 0) {
        // connect to the local database server
        mongoClient = new MongoClient();
    } else {
        mongoClient = new MongoClient(new MongoClientURI(args[0]));
    }
    // get handle to "mydb" database
    MongoDatabase database = mongoClient.getDatabase("mydb");
    database.drop();
    // get a handle to the "test" collection
    MongoCollection<Document> collection = database.getCollection("test");
    // drop all the data in it
    collection.drop();
    // getting a list of databases
    for (String name : mongoClient.listDatabaseNames()) {
        System.out.println(name);
    }
    // drop a database
    mongoClient.getDatabase("databaseToBeDropped").drop();
    // create a collection
    database.createCollection("cappedCollection", new CreateCollectionOptions().capped(true).sizeInBytes(0x100000));
    for (String name : database.listCollectionNames()) {
        System.out.println(name);
    }
    // drop a collection:
    collection.drop();
    // create an ascending index on the "i" field
    collection.createIndex(Indexes.ascending("i"));
    // list the indexes on the collection
    for (final Document index : collection.listIndexes()) {
        System.out.println(index.toJson());
    }
    // create a text index on the "content" field
    collection.createIndex(Indexes.text("content"));
    collection.insertOne(new Document("_id", 0).append("content", "textual content"));
    collection.insertOne(new Document("_id", 1).append("content", "additional content"));
    collection.insertOne(new Document("_id", 2).append("content", "irrelevant content"));
    // Find using the text index
    long matchCount = collection.count(text("textual content -irrelevant"));
    System.out.println("Text search matches: " + matchCount);
    // Find using the $language operator
    Bson textSearch = text("textual content -irrelevant", new TextSearchOptions().language("english"));
    matchCount = collection.count(textSearch);
    System.out.println("Text search matches (english): " + matchCount);
    // Find the highest scoring match
    Document projection = new Document("score", new Document("$meta", "textScore"));
    Document myDoc = collection.find(textSearch).projection(projection).first();
    System.out.println("Highest scoring document: " + myDoc.toJson());
    // Run a command
    Document buildInfo = database.runCommand(new Document("buildInfo", 1));
    System.out.println(buildInfo);
    // release resources
    database.drop();
    mongoClient.close();
}
Also used : MongoClient(com.mongodb.MongoClient) MongoClientURI(com.mongodb.MongoClientURI) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) TextSearchOptions(com.mongodb.client.model.TextSearchOptions) Document(org.bson.Document) MongoDatabase(com.mongodb.client.MongoDatabase) Bson(org.bson.conversions.Bson)

Aggregations

MongoClient (com.mongodb.MongoClient)288 Test (org.junit.Test)73 ServerAddress (com.mongodb.ServerAddress)48 MongoClientURI (com.mongodb.MongoClientURI)47 Document (org.bson.Document)47 MongoDatabase (com.mongodb.client.MongoDatabase)43 SimpleMongoDbFactory (org.springframework.data.mongodb.core.SimpleMongoDbFactory)40 Before (org.junit.Before)28 MongoDbAvailable (org.springframework.integration.mongodb.rules.MongoDbAvailable)28 BasicDBObject (com.mongodb.BasicDBObject)25 MongoCredential (com.mongodb.MongoCredential)24 DB (com.mongodb.DB)22 ArrayList (java.util.ArrayList)21 IOException (java.io.IOException)19 AbstractBatchingMessageGroupStore (org.springframework.integration.store.AbstractBatchingMessageGroupStore)16 MessageGroupStore (org.springframework.integration.store.MessageGroupStore)16 DBCollection (com.mongodb.DBCollection)15 MongoException (com.mongodb.MongoException)15 MongoClientOptions (com.mongodb.MongoClientOptions)14 GenericMessage (org.springframework.messaging.support.GenericMessage)14