Example usage for com.mongodb Mongo Mongo

List of usage examples for com.mongodb Mongo Mongo

Introduction

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

Prototype

@Deprecated
public Mongo() 

Source Link

Document

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

Usage

From source file:dbscan.DBScanReducer.java

License:Apache License

DBScanReducer() throws java.net.UnknownHostException {
    super();//from   w w w.  j ava  2 s.c  o  m
    m = new Mongo();
    db = m.getDB("p");
    boolean auth = db.authenticate("username", "password".toCharArray());
    if (!auth)
        throw new RuntimeException("Login error");
    collection = db.getCollection("points");
}

From source file:de.fhg.igd.mongomvcc.impl.MongoDBVDatabase.java

License:Open Source License

@Override
public void connect(String name) throws VException {
    Mongo mongo;/*from   w ww . j  av a2  s .com*/
    try {
        mongo = new Mongo();
    } catch (UnknownHostException e) {
        throw new VException("Unknown host", e);
    }
    connectInternal(name, mongo);
}

From source file:dev.j.regere.respository.MongoIntermediatePersistedTable.java

License:Apache License

@Override
public void init() {
    try {/*from w  ww.  ja v  a 2  s .c  o  m*/
        logger.info("loading mongodb with default details");
        dbCollection = new Mongo().getDB("regere_db").getCollection("regere_intermediate_table");
        logger.info("mongodb successfully loaded");
    } catch (UnknownHostException e) {
        throw new RuntimeException("Error loading mognodb : ", e);
    }
}

From source file:edu.sjsu.carbonated.client.MongoDBDOA.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server
    Mongo m = new Mongo();

    // get handle to "mydb"
    DB db = m.getDB("mydb");

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get a list of the collections in this database and print them out
    Set<String> colls = db.getCollectionNames();
    for (String s : colls) {
        System.out.println(s);/*from w ww .j a  va 2s.c  o m*/
    }

    // get a collection object to work with
    DBCollection coll = db.getCollection("testCollection");

    // drop all the data in it
    coll.drop();

    // make a document and insert it
    BasicDBObject doc = new BasicDBObject();

    doc.put("test", new AlbumResource("name", "desc", "user", "asdf"));
    doc.put("name", "MongoDB");
    doc.put("type", "database");
    doc.put("count", 1);

    BasicDBObject info = new BasicDBObject();

    info.put("x", 203);
    info.put("y", 102);

    doc.put("info", info);

    coll.insert(doc);

    // get it (since it's the only one in there since we dropped the rest earlier on)
    DBObject myDoc = coll.findOne();
    System.out.println(myDoc);

    // now, lets add lots of little documents to the collection so we can explore queries and cursors
    for (int i = 0; i < 100; i++) {
        coll.insert(new BasicDBObject().append("i", i));
    }
    System.out
            .println("total # of documents after inserting 100 small ones (should be 101) " + coll.getCount());

    //  lets get all the documents in the collection and print them out
    DBCursor cur = coll.find();
    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    //  now use a query to get 1 document out
    BasicDBObject query = new BasicDBObject();
    query.put("i", 71);
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    //  now use a range query to get a larger subset
    query = new BasicDBObject();
    query.put("i", new BasicDBObject("$gt", 50)); // i.e. find all where i > 50
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    // range query with multiple contstraings
    query = new BasicDBObject();
    query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e.   20 < i <= 30
    cur = coll.find(query);

    while (cur.hasNext()) {
        System.out.println(cur.next());
    }

    // create an index on the "i" field
    coll.createIndex(new BasicDBObject("i", 1)); // create index on "i", ascending

    //  list the indexes on the collection
    List<DBObject> list = coll.getIndexInfo();
    for (DBObject o : list) {
        System.out.println(o);
    }

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    // see if any previous operation had an error
    System.out.println("Previous error : " + db.getPreviousError());

    // force an error
    db.forceError();

    // See if the last operation had an error
    System.out.println("Last error : " + db.getLastError());

    db.resetError();
}

From source file:es.devcircus.mongodb_examples.hello_world.Main.java

License:Open Source License

/**
 * Mtodo que nos permite crear una nueva conexin con nuestra base de 
 * datos.//from w  w  w.  jav a 2  s  .c o  m
 */
public static void makingAConnection() {
    try {
        System.out.println("---------------------------------------------------------------");
        System.out.println(" Making A Connection                                           ");
        System.out.println("---------------------------------------------------------------");
        System.out.println();

        /*Making A Connection
         To make a connection to a MongoDB, you need to have at the minimum, 
         * the name of a database to connect to. The database doesn't have 
         * to exist - if it doesn't, MongoDB will create it for you.
         Additionally, you can specify the server address and port when connecting. 
         * The following example shows three ways to connect to the database 
         * mydb on the local machine :*/

        Mongo m = new Mongo();
        // or
        //Mongo m = new Mongo( "localhost" );
        // or
        //Mongo m = new Mongo( "localhost" , 27017 );

        db = m.getDB(DB_NAME);

        System.out.println(" Conexin establecida..: " + db.getName());

        /*At this point, the db object will be a connection to a MongoDB 
         * server for the specified database. With it, you can do further 
         * operations. 
                
         Note: The Mongo object instance actually represents a pool of connections 
         * to the database; you will only need one object of class Mongo 
         * even with multiple threads.  See the concurrency doc page for more 
         * information.
                
         The Mongo class is designed to be thread safe and shared among threads. 
         * Typically you create only 1 instance for a given DB cluster and 
         * use it across your app. If for some reason you decide to create 
         * many mongo intances, note that:
                
         all resource usage limits (max connections, etc) apply per mongo instance
         to dispose of an instance, make sure you call mongo.close() to clean 
         * up resources*/
    } catch (UnknownHostException | MongoException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:es.devcircus.mongodb_examples.hello_world.Main.java

License:Open Source License

/**
 * Mtodo en el que se muestran algunas funciones de administracin.
 *//*  www  .j  a va  2 s . co  m*/
public static void quickTourOfTheAdministrativeFunctions() {
    try {
        System.out.println();
        System.out.println("---------------------------------------------------------------");
        System.out.println(" Quick Tour of the Administrative Functions                    ");
        System.out.println("---------------------------------------------------------------");
        System.out.println();

        /*Quick Tour of the Administrative Functions
         Getting A List of Databases
         You can get a list of the available databases:*/

        Mongo m = new Mongo();

        for (String s : m.getDatabaseNames()) {
            System.out.println(" - " + s);
        }

        /*Dropping A Database
         You can drop a database by name using the Mongo object:*/

        m.dropDatabase(DB_NAME);
    } catch (UnknownHostException | MongoException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:eu.cassandra.server.threads.RunsContextListener.java

License:Apache License

@Override
public void contextInitialized(ServletContextEvent arg0) {
    ServletContext context = arg0.getServletContext();
    runs = new HashMap<String, Future<?>>();
    context.setAttribute("MY_RUNS", runs);
    // Delete all unfinished thread from db and their dbs:
    DBObject query = new BasicDBObject();
    query.put("ended", -1);
    DBCursor cursor = DBConn.getConn().getCollection(MongoRuns.COL_RUNS).find(query);
    while (cursor.hasNext()) {
        DBObject run = cursor.next();// www  .j a  v a  2  s  . c o  m
        DBConn.getConn().getCollection(MongoRuns.COL_RUNS).remove(run);
        String run_id = run.get("_id").toString();
        Mongo mongo;
        try {
            mongo = new Mongo();
            mongo.dropDatabase(run_id);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (MongoException e) {
            e.printStackTrace();
        }
    }
}

From source file:eu.delving.core.util.MongoFactory.java

License:EUPL

@Override
public void afterPropertiesSet() throws Exception {
    if (testContext) {
        this.mongo = new Mongo();
    } else {// w w w  .jav  a2  s . co  m
        if (mongoAddresses.isEmpty() || mongoAddresses.size() < 3) {
            throw new IllegalStateException("Please configure at least 3 instances of Mongo for production.");
        }
        mongoOptions.connectionsPerHost = 100;
        this.mongo = new Mongo(mongoAddresses, mongoOptions);
    }
}

From source file:eu.delving.services.MockServices.java

License:EUPL

private static void dropMongoDatabase() throws UnknownHostException {
    LaunchProperties launchProperties = new LaunchProperties(Arrays.asList("services.mongo.dbName"));
    String mongoName = launchProperties.getProperty("services.mongo.dbName");
    Mongo mongo = new Mongo();
    DB db = mongo.getDB(mongoName);//from  w  w  w .  j  a  va 2  s . c  om
    db.dropDatabase();
}

From source file:eu.trentorise.smartcampus.mobility.test.script.ConvertData.java

License:Apache License

public ConvertData() throws UnknownHostException, MongoException {
    super();// w  ww. j a v  a 2s . c  om
    template = new MongoTemplate(new Mongo(), "smartsayback");
    targetTemplate = new MongoTemplate(new Mongo(), "mobility-domain");
}