Example usage for com.mongodb MongoClient getDatabase

List of usage examples for com.mongodb MongoClient getDatabase

Introduction

In this page you can find the example usage for com.mongodb MongoClient getDatabase.

Prototype

public MongoDatabase getDatabase(final String databaseName) 

Source Link

Usage

From source file:com.imos.sample.NewClass.java

public static void main(String[] args) {
    try {// ww  w  .  j  a v  a 2  s  .  c o m
        MongoClient mongoClient = new MongoClient();
        MongoDatabase db = mongoClient.getDatabase("test");

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);

        Document address = new Document().append("street", "2 Avenue").append("zipcode", "10075")
                .append("building", "1480").append("coord", asList(-73.9557413, 40.7720266));

        db.getCollection("restaurants")
                .insertOne(
                        new Document("address", address)
                                .append("borough",
                                        "Manhattan")
                                .append("cuisine",
                                        "Italian")
                                .append("grades", asList(
                                        new Document().append("date", format.parse("2014-10-01T00:00:00Z"))
                                                .append("grade", "A").append("score", 11),
                                        new Document().append("date", format.parse("2014-01-16T00:00:00Z"))
                                                .append("grade", "B").append("score", 17)))
                                .append("name", "Vella").append("restaurant_id", "41704620"));

        FindIterable<Document> iterable = db.getCollection("restaurants").find();

        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document);
            }
        });

        db.getCollection("restaurants").updateOne(address, new Document()
                //                    .append("street", "5th Avenue")
                .append("zipcode", "10075").append("building", "1480")
                .append("coord", asList(-73.9557413, 40.7720266)));

        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document);
            }
        });

    } catch (ParseException ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.imos.sample.SampleMongoDB.java

public static void main(String[] args) {
    MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017");
    MongoClient mongoClient = new MongoClient(connectionString);
    MongoDatabase database = mongoClient.getDatabase("sampledb");
    MongoCollection<Document> collection = database.getCollection("sampleLog");
    System.out.println(collection.count());
    MongoCursor<Document> cursor = collection.find().iterator();
    ObjectMapper mapper = new ObjectMapper();
    try {//from   w ww . j a v  a  2s  .  co m
        while (cursor.hasNext()) {
            try {
                System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cursor.next()));
            } catch (JsonProcessingException ex) {
                Logger.getLogger(SampleMongoDB.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } finally {
        cursor.close();
    }
}

From source file:com.inflight.rest.AddFlightService.java

@SuppressWarnings("resource")
@POST//from w ww.  j  a v  a2s .com
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String signup(@FormParam("username") String username, @FormParam("confirmCode") String confirmCode,
        @FormParam("fromLocation") String fromLocation, @FormParam("toLocation") String toLocation)
        throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("location");

    Document doc = collection.find(or(eq("confirmCode", confirmCode), eq("toLocation", toLocation))).first();
    if (doc == null) {
        Document newDoc = new Document("username", username).append("confirmCode", confirmCode)
                .append("fromLocation", fromLocation).append("toLocation", toLocation);

        collection.insertOne(newDoc);
        result = "{\"success\": true}";
        return result;
    } else {
        result = "{\"success\": false, \"message\": \"Booking Reference or To Location already exists\"}";
        return result;
    }
}

From source file:com.inflight.rest.LoginService.java

@SuppressWarnings("resource")
@POST//  w w  w  .j  a  v a 2  s .  com
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String login(@FormParam("username") String username, @FormParam("password") String password)
        throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("users");

    Document doc = collection.find(eq("username", username)).first();

    if (doc != null) {
        String actualPass = doc.get("password").toString();
        if (Password.check(password, actualPass)) {
            result = "{\"success\": true}";
            return result;
        } else {
            result = "{\"success\": false, \"message\": \"Invalid Password\"}";
            return result;
        }
    } else {
        result = "{\"success\": false, \"message\": \"Invalid Username\"}";
        return result;
    }

}

From source file:com.inflight.rest.SignUpService.java

@SuppressWarnings("resource")
@POST//w w w .ja v a2s .  co  m
@Consumes("application/x-www-form-urlencoded")
@Produces(MediaType.APPLICATION_JSON)
public String signup(@FormParam("username") String username, @FormParam("password") String password,
        @FormParam("email") String email) throws Exception {

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);
    String result = "";

    MongoDatabase database = mongoClient.getDatabase("inflight");
    MongoCollection<Document> collection = database.getCollection("users");

    Document doc = collection.find(or(eq("username", username), eq("email", email))).first();
    if (doc == null) {
        Document newDoc = new Document("username", username)
                .append("password", Password.getSaltedHash(password)).append("email", email);

        collection.insertOne(newDoc);
        result = "{\"success\": true}";
        return result;
    } else {
        result = "{\"success\": false, \"message\": \"Username or Email already exists\"}";
        return result;
    }

}

From source file:com.inflight.rest.ViewPlaces.java

@SuppressWarnings("resource")
@GET/*from w w  w.jav a  2 s  . c om*/
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public String getLocations() {

    JSONArray jsonArr = new JSONArray();

    MongoClientURI connectionString = new MongoClientURI(
            "mongodb://ramkrish:1234567@ds029446.mlab.com:29446/inflight");
    MongoClient mongoClient = new MongoClient(connectionString);

    MongoDatabase database = mongoClient.getDatabase("inflight");

    MongoCollection<Document> collection = database.getCollection("location");

    MongoCursor<Document> cursor = collection.find().iterator();
    try {
        while (cursor.hasNext()) {
            jsonArr.put(cursor.next());

        }
    } finally {
        cursor.close();
    }

    return jsonArr.toString();
}

From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlMongoDb.java

License:Open Source License

MongoCollection<Document> getCollection(MongoClient mongoClient) throws IOException {
    if (StringUtils.isEmpty(databaseName))
        throw new IOException("No database name.");
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    if (StringUtils.isEmpty(collectionName))
        throw new IOException("No collection name.");
    return db.getCollection(collectionName);
}

From source file:com.jaeksoft.searchlib.crawler.database.DatabaseCrawlMongoDb.java

License:Open Source License

@Override
public String test() throws Exception {
    URI uri = new URI(getUrl());
    StringBuilder sb = new StringBuilder();
    if (!"mongodb".equals(uri.getScheme()))
        throw new SearchLibException(
                "Wrong scheme: " + uri.getScheme() + ". The URL should start with: mongodb://");
    MongoClient mongoClient = null;
    try {//w w w .  ja  v a2  s.  co  m
        mongoClient = getMongoClient();
        sb.append("Connection established.");
        sb.append(StringUtils.LF);
        if (!StringUtils.isEmpty(databaseName)) {
            MongoDatabase db = mongoClient.getDatabase(databaseName);
            if (db == null)
                throw new SearchLibException("Database not found: " + databaseName);
            MongoIterable<String> collections = db.listCollectionNames();
            if (collections == null)
                throw new SearchLibException("No collection found.");
            sb.append("Collections found:");
            sb.append(StringUtils.LF);
            for (String collection : collections) {
                sb.append(collection);
                sb.append(StringUtils.LF);
            }
            if (!StringUtils.isEmpty(collectionName)) {
                MongoCollection<?> dbCollection = db.getCollection(collectionName);
                if (dbCollection == null)
                    throw new SearchLibException("Collection " + collectionName + " not found.");
                sb.append(
                        "Collection " + collectionName + " contains " + dbCollection.count() + " document(s).");
                sb.append(StringUtils.LF);
                if (!StringUtils.isEmpty(criteria)) {
                    long count = dbCollection.count(getCriteriaObject());
                    sb.append("Query returns " + count + " document(s).");
                    sb.append(StringUtils.LF);
                }
            }
        }
    } finally {
        if (mongoClient != null)
            mongoClient.close();
    }
    return sb.toString();
}

From source file:com.khubla.cbean.mongokv.MongoKVService.java

License:Open Source License

@Override
public void delete(CBeanKey cBeanKey) throws KVServiceException {
    MongoClient mongoClient = null;
    try {//from   w  ww  . j a  v  a 2  s.  c o  m
        /*
         * get a pooled mongo connection
         */
        mongoClient = mongoClientPool.borrowObject();
        mongoClient.getDatabase(cBeanUrl.getClusterName());
        /*
         * query
         */
        // final Location location = new Location(new Namespace(clusterName), url);
        // final DeleteValue dv = new DeleteValue.Builder(location).build();
        // riakClient.execute(dv);
        logger.info("Deleted asset '" + cBeanKey.getKey() + "'");
    } catch (final Exception e) {
        logger.info("Unable to delete asset '" + cBeanKey.getKey() + "'");
        throw new KVServiceException(e);
    } finally {
        try {
            if (null != mongoClient) {
                mongoClientPool.returnObject(mongoClient);
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.mycompany.citysearchnosql.Executioner.java

public static void main(final String[] args) {

    // 1. Connect to MongoDB instance running on localhost
    MongoClient mongoClient = new MongoClient();

    // Access database named 'test'
    MongoDatabase database = mongoClient.getDatabase("test");

    // Access collection named 'restaurants'
    MongoCollection<Document> collection = database.getCollection("restaurants");

    // 2. Insert 
    List<Document> documents = asList(
            new Document("name", "Sun Bakery Trattoria").append("stars", 4).append("categories",
                    asList("Pizza", "Pasta", "Italian", "Coffee", "Sandwiches")),
            new Document("name", "Blue Bagels Grill").append("stars", 3).append("categories",
                    asList("Bagels", "Cookies", "Sandwiches")),
            new Document("name", "Hot Bakery Cafe").append("stars", 4).append("categories",
                    asList("Bakery", "Cafe", "Coffee", "Dessert")),
            new Document("name", "XYZ Coffee Bar").append("stars", 5).append("categories",
                    asList("Coffee", "Cafe", "Bakery", "Chocolates")),
            new Document("name", "456 Cookies Shop").append("stars", 4).append("categories",
                    asList("Bakery", "Cookies", "Cake", "Coffee")));

    collection.insertMany(documents);/*from  www . j a va  2  s. com*/

    // 3. Query 
    List<Document> results = collection.find().into(new ArrayList<>());

    // 4. Create Index 
    collection.createIndex(Indexes.ascending("name"));
    // 5. Perform Aggregation
    collection.aggregate(asList(match(eq("categories", "Bakery")), group("$stars", sum("count", 1))));

    mongoClient.close();
}