Example usage for com.mongodb.client MongoDatabase getCollection

List of usage examples for com.mongodb.client MongoDatabase getCollection

Introduction

In this page you can find the example usage for com.mongodb.client MongoDatabase getCollection.

Prototype

MongoCollection<Document> getCollection(String collectionName);

Source Link

Document

Gets a collection.

Usage

From source file:com.imaginea.mongodb.services.impl.DocumentServiceImpl.java

License:Apache License

/**
 * Gets the list of documents inside a collection in a database in mongo to which user is
 * connected to./*from w ww  . j  av  a 2  s.c  o m*/
 *
 * @param dbName Name of Database
 * @param collectionName Name of Collection from which to get all Documents
 * @param command Name of the Command to be executed
 * @param queryStr query to be performed. In case of empty query {} return all
 * @param keys Keys to be present in the resulted docs.
 * @param limit Number of docs to show.
 * @param skip Docs to skip from the front.
 * @param allKeys
 * @return List of all documents.
 * @throws DatabaseException throw super type of UndefinedDatabaseException
 * @throws ValidationException throw super type of
 *         EmptyDatabaseNameException,EmptyCollectionNameException
 * @throws CollectionException throw super type of UndefinedCollectionException
 * @throws DocumentException exception while performing get doc list
 */

public JSONObject executeQuery(String dbName, String collectionName, String command, String queryStr,
        String keys, String sortBy, int limit, int skip, boolean allKeys) throws ApplicationException,
        CollectionException, DocumentException, ValidationException, JSONException {

    if (dbName == null) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database name is null");
    }
    if (dbName.equals("")) {
        throw new DatabaseException(ErrorCodes.DB_NAME_EMPTY, "Database Name Empty");
    }

    try {
        // List<String> databaseNames = databaseService.getDbList();
        // if (!databaseNames.contains(dbName)) {
        //   throw new DatabaseException(ErrorCodes.DB_DOES_NOT_EXISTS,
        //       "DB with name [" + dbName + "]DOES_NOT_EXIST");
        // }
        MongoDatabase db = mongoInstance.getDatabase(dbName);
        if (collectionName == null) {
            throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection name is null");
        }
        if (collectionName.equals("")) {
            throw new CollectionException(ErrorCodes.COLLECTION_NAME_EMPTY, "Collection Name Empty");
        }
        if (!collectionService.getCollList(dbName).contains(collectionName)) {
            throw new CollectionException(ErrorCodes.COLLECTION_DOES_NOT_EXIST, "Collection with name ["
                    + collectionName + "] DOES NOT EXIST in Database [" + dbName + "]");
        }

        MongoCollection<Document> collection = db.getCollection(collectionName);

        return QueryExecutor.executeQuery(db, collection, collectionName, command, queryStr, keys, sortBy,
                limit, skip, allKeys);
    } catch (MongoException e) {
        throw new DocumentException(ErrorCodes.QUERY_EXECUTION_EXCEPTION, e.getMessage());
    }
}

From source file:com.imaginea.mongodb.services.impl.GridFSServiceImpl.java

License:Apache License

private JSONObject executeDrop(MongoDatabase db, String bucketName) throws JSONException {
    db.getCollection(bucketName + ".files").drop();
    db.getCollection(bucketName + ".chunks").drop();
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("success", true);
    return jsonObject;
}

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

public static void main(String[] args) {
    try {//  w ww .  j  av  a2  s .  c om
        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  w  w.j  a  v  a  2 s . c  o  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.imos.sample.SampleMongoDB.java

private static void sampleOne(MongoDatabase database) throws JsonProcessingException {
    MongoCollection<Document> collection = database.getCollection("test");
    Document doc = new Document("name", "MongoDB").append("type", "database").append("count", 1)
            .append("versions", Arrays.asList("v3.2", "v3.0", "v2.6"))
            .append("info", new Document("x", 203).append("y", 102));
    //        collection.insertOne(doc);
    System.out.println(collection.count());
    MongoCursor<Document> cursor = collection.find().iterator();
    ObjectMapper mapper = new ObjectMapper();
    //        try {
    //            while (cursor.hasNext()) {
    ////                System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(cursor.next()));
    //            }
    //        } finally {
    //            cursor.close();
    //        }/*from w  ww.  j a  v a  2s  .c  o m*/

    Document myDoc = collection.find(eq("type", "database")).first();
    System.out.println(myDoc.toJson());
}

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

@SuppressWarnings("resource")
@POST/* ww w  .jav a2  s.c  o m*/
@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/*from   w w  w  . ja v  a  2 s .c o  m*/
@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//from  ww  w  .  ja  v a  2 s  .  c o 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   ww w  . jav  a 2  s . com*/
@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.cache.MongoDbCrawlCache.java

License:Open Source License

@Override
public void init(String configString) throws IOException {
    rwl.w.lock();//  www  .j  a v a2  s.  c o m
    try {
        closeNoLock();
        final MongoClientURI connectionString = new MongoClientURI(configString);
        mongoClient = new MongoClient(connectionString);
        final MongoDatabase database = mongoClient.getDatabase(
                connectionString.getDatabase() == null ? DEFAULT_DATABASE : connectionString.getDatabase());
        metaCollection = database.getCollection(META_COLLECTION);
        metaCollection.createIndex(Document.parse("{\"uri\":1}"));
        indexedCollection = database.getCollection(INDEXED_COLLECTION);
        indexedCollection.createIndex(Document.parse("{\"uri\":1}"));
        contentGrid = GridFSBuckets.create(database);
    } finally {
        rwl.w.unlock();
    }
}