Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient() 

Source Link

Document

Creates an instance based on a (single) mongodb node (localhost, default port).

Usage

From source file:com.iluwatar.caching.DbManager.java

License:Open Source License

/**
 * Connect to DB/*  w ww  .ja va 2s  . c  om*/
 */
public static void connect() throws ParseException {
    useMongoDB = true;
    mongoClient = new MongoClient();
    db = mongoClient.getDatabase("test");
}

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

public static void main(String[] args) {
    try {//from ww w  .j  av  a 2 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.kurniakue.trxreader.data.KurniaKueDb.java

public static void init() {
    try {//w w  w.java  2 s  .co m
        mongoClient = new MongoClient();
        db = mongoClient.getDB(DB_NAME);
        initCollections();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.malsolo.mongodb.humongous.config.Application.java

@Bean
public Mongo mongo() throws Exception {
    Mongo mongo = new MongoClient();
    mongo.setWriteConcern(WriteConcern.SAFE);
    return mongo;
}

From source file:com.malsolo.mongodb.humongous.driver.Main.java

public static void main(String... args) throws UnknownHostException {

    MongoClient mongoClient = new MongoClient();
    DB db = mongoClient.getDB("news");

    Set<String> colls = db.getCollectionNames();

    for (String s : colls) {
        System.out.println(s);// w  w  w  . j  a va 2  s .c o  m
    }

    DBCollection coll = db.getCollection("article");

    BasicDBObject doc = new BasicDBObject("authorId", UUID.randomUUID()).append("author", "Driver")
            .append("date", new Date()).append("title", "Title");
    coll.insert(doc);

    DBObject myDoc = coll.findOne();
    System.out.println(myDoc);

    System.out.println(coll.getCount());

    try (DBCursor cursor = coll.find()) {
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    }

}

From source file:com.melayer.eco.config.MeConfigDb.java

@Bean
public MeMongoFactoryMultiTenenacy multitenenatMongoFactoty() throws Exception {

    MeMongoFactoryMultiTenenacy multitenenatMongoFactoty = new MeMongoFactoryMultiTenenacy(new MongoClient(),
            "melayer");

    return multitenenatMongoFactoty;
}

From source file:com.morphiatest.businesslogic.App.java

/**
 * @param args the command line arguments
 *///  w w  w . j  a  v  a2 s  .  c  om
public static void main(String[] args) throws UnknownHostException {
    // given
    Dish dish = new Dish();
    Vegetable vegetable = new Vegetable();
    vegetable.setName("pea");
    vegetable.setOriginFarm("Maggies Farm");
    dish.setMainIngredient(vegetable);

    // when
    Morphia morphia = new Morphia();
    MongoClient client = new MongoClient();
    Datastore datastore = morphia.createDatastore(client, "test");

    datastore.getDB().dropDatabase();

    datastore.save(vegetable);
    datastore.save(dish);

    Query<Dish> query = datastore.createQuery(Dish.class);
    query.get();

    // then in console
    // WARNING: Class com.morphiatest.genericdataobjects.Ingredient is stored in the 'Ingredient' collection but a reference was found for this type to another collection, 'Vegetable'. The reference will be loaded using the class anyway. { "$ref" : "Vegetable", "$id" : "548de3d0389751c97913091c" }
}

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 w  w w.j  av a  2s.  c o  m*/

    // 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();
}

From source file:com.mycompany.letsmine.config.SpringMongoConfig.java

public @Bean MongoDbFactory mongoDbFactory() throws Exception {
    return new SimpleMongoDbFactory(new MongoClient(), "LetsMine");
}

From source file:com.mycompany.mavenproject2.AddCatController.java

public void InsertMongo() {
    client = new MongoClient();
    db = client.getDatabase("FinalDemo");
    MongoCollection col = db.getCollection("CategoryDetail");
    final Document seedData = createSeedData();
    col.insertOne(seedData);/*from   ww w  .j ava 2s. co m*/

    LocalName.clear();
    CatName.clear();
}