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.DA.assignment1.Query.Question2.java

public void Answer() {

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase("test");

    AggregateIterable<Document> iterable = db.getCollection("movies")
            .aggregate(asList(new Document("$unwind", "$generes"),
                    new Document("$group",
                            new Document("_id", "$generes").append("count", new Document("$sum", 1))),
                    new Document("$sort", new Document("count", -1))));

    iterable.forEach(new Block<Document>() {
        @Override/*w  w  w.  j a  v  a  2 s.  c  o m*/
        public void apply(final Document document) {
            System.out.println(document.toJson());
        }
    });

}

From source file:com.damanzano.mongohw2_2.MongoHW2_2.java

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient();
    DB db = client.getDB("students");
    DBCollection collection = db.getCollection("grades");

    DBCursor allGrades = collection.find(new BasicDBObject("type", "homework"))
            .sort(new BasicDBObject("student_id", 1).append("score", 1));
    try {//from   www  . j  a v  a2s  .co  m
        String studentId = "";
        while (allGrades.hasNext()) {
            DBObject grade = allGrades.next();
            System.out.println(grade);
            if (!studentId.equalsIgnoreCase(((Integer) grade.get("student_id")).toString())) {
                System.out.println("Deleting grade " + grade.get("_id").toString() + " for student "
                        + grade.get("student_id").toString());
                collection.remove(grade);
            }
            studentId = ((Integer) grade.get("student_id")).toString();
        }
    } finally {
        allGrades.close();
    }
}

From source file:com.demo.mongodb.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override/*from w w  w .  j a va 2s . c om*/
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template template = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                List<Document> results = collection.aggregate(asList(
                        new Document("$group",
                                new Document("_id", "$value").append("count", new Document("$sum", 1))),
                        new Document("$match", new Document("count", new Document("$lte", 2))),
                        new Document("$sort", new Document("_id", 1)))).into(new ArrayList<Document>());

                int answer = 0;
                for (Document cur : results) {
                    answer += (Double) cur.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                template.process(answerMap, writer);
            } catch (Exception e) {
                e.printStackTrace();
                halt(500);
            }
            return writer;
        }
    });
}

From source file:com.enlightendev.mongodb.MongoDBSparkFreemarkerStyle.java

License:Apache License

public static void main(String[] args) {
    final Configuration configuration = new Configuration();
    configuration.setClassForTemplateLoading(MongoDBSparkFreemarkerStyle.class, "/freemarker");

    MongoClient client = new MongoClient();

    MongoDatabase database = client.getDatabase("m101");
    final MongoCollection<Document> collection = database.getCollection("funnynumbers");

    Spark.get(new Route("/") {
        @Override/*from   w ww. ja va 2s .c  o  m*/
        public Object handle(final Request request, final Response response) {
            StringWriter writer = new StringWriter();
            try {
                Template template = configuration.getTemplate("answer.ftl");

                // Not necessary yet to understand this.  It's just to prove that you
                // are able to run a command on a mongod server
                List<Document> results = collection.aggregate(asList(
                        new Document("$group",
                                new Document("_id", "$value").append("count", new Document("$sum", 1))),
                        new Document("$match", new Document("count", new Document("$lte", 2))),
                        new Document("$sort", new Document("_id", 1)))).into(new ArrayList<Document>());

                int answer = 0;
                for (Document cur : results) {
                    answer += (Double) cur.get("_id");
                }

                Map<String, String> answerMap = new HashMap<String, String>();
                answerMap.put("answer", Integer.toString(answer));

                template.process(answerMap, writer);
            } catch (Exception e) {
                e.printStackTrace();
                halt(500);
            }
            return writer;
        }
    });
}

From source file:com.example.MongoDBContainerDemo.java

License:Apache License

@Override
protected void init(VaadinRequest request) {
    this.setContent(tabSheet);
    try {/*from  www  .  j a  va 2s .c  o m*/
        mongoOperations = new MongoTemplate(new MongoClient(), "scratch");
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    // mongoOperations.remove(new Query(), Person.class);
    // generateRecords();

    final AbstractMongoDemo basic = new BasicMongoDemo(mongoOperations).initLayout();
    final AbstractMongoDemo buffered = new BufferedMongoDemo(mongoOperations).initLayout();

    tabSheet.addTab(basic, "Basic");
    tabSheet.addTab(buffered, "Buffered");

    tabSheet.setSelectedTab(basic);

    tabSheet.addSelectedTabChangeListener(new TabSheet.SelectedTabChangeListener() {
        @Override
        public void selectedTabChange(TabSheet.SelectedTabChangeEvent event) {
            if (tabSheet.getSelectedTab().equals(buffered)) {
                buffered.mongoContainer.refresh();
                buffered.table.refreshRowCache();
            } else {
                basic.mongoContainer.refresh();
                basic.table.refreshRowCache();
            }
        }
    });
}

From source file:com.example.rapidoid.morphia.dev_issue.services.MorphiaService.java

License:Open Source License

private void createDatastoreConnection() {
    //Create Mongo Connection
    morphia = new org.mongodb.morphia.Morphia();
    morphia.mapPackage("com.example.rapidoid.morphia.dev_issue.services.models");
    client = new MongoClient();
    datastore = morphia.createDatastore(client, "rapidoid_morphia_example");
    datastore.ensureIndexes();/*from   w  ww. j ava2 s  .  c o  m*/
}

From source file:com.exorath.exodata.impl.IDataAPI.java

License:Apache License

public IDataAPI() {
    this.client = new MongoClient();
}

From source file:com.github.lsiu.vaadin.mongocontainer.GenerateSampleData.java

public void run() {
    try {/*ww  w.j ava 2 s. c o m*/
        client = new MongoClient();
        db = client.getDB("test");

        convertXmlDataToJson();
    } catch (IOException | ParserConfigurationException | SAXException e) {
        throw new RuntimeException("RuntimeException. See cause.", e);
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:com.grallandco.mongodb.beersample.ConnectionManager.java

License:Open Source License

/**
 * Connect to MongoDB when the Server starts.
 *
 * @param sce the ServletContextEvent (not used here).
 *///from   w ww .  j av a2 s . co  m
@Override
public void contextInitialized(ServletContextEvent sce) {
    try {
        db = new MongoClient().getDB("beers");
    } catch (IOException ex) {
        logger.log(Level.SEVERE, ex.getMessage());
    }
}

From source file:com.ifeng.vdn.report.rest.data.mongodb.ApplicationConfiguration.java

License:Apache License

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