Example usage for com.mongodb DBCollection findOne

List of usage examples for com.mongodb DBCollection findOne

Introduction

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

Prototype

@Nullable
public DBObject findOne() 

Source Link

Document

Get a single document from collection.

Usage

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 ww . ja v  a  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.mycompany.mongodemo.MongoDemoClass.java

public static void main(String[] args) {
    MongoClient mongo = new MongoClient("localhost", 27017);
    /*/*from w w w . ja v a2 s.co m*/
    first create database and collection(table) in mongodb
    code
        use demodb // to create db
        db.createCollection("users") // create table users in db
     */
    DB db = mongo.getDB("demodb");

    DBCollection col = db.getCollection("users");

    // creating list of POST
    BasicDBList postList = new BasicDBList();
    postList.add("a1"); // add post reference in list
    postList.add("a2");
    postList.add("a3");
    // create nested element : posts
    BasicDBObject posts = new BasicDBObject("publicPost", postList).append("privatePost", postList)
            .append("exclusivePost", postList);

    // create insert document 
    BasicDBObject doc = new BasicDBObject("firstName", "vishal").append("lastName", "patel")
            .append("email", "vishal.6794@gmail.com").append("userName", "im_vishal")
            .append("password", "admin").append("userType", 1).append("lastAccessTime", new Date())
            .append("posts", posts).append("rating", 10).append("verified", true);

    // insert into collection using insert method
    col.insert(doc);

    /*
    display first document from collection
    in this case our collection is users
    */

    DBObject mydoc = col.findOne();
    System.out.println(mydoc);
}

From source file:com.nlp.twitterstream.MongoUtil.java

License:Open Source License

/**
 * Get first document that matches selection in database
 * //w w w  .  j a v a2s.co m
 * @param collection
 *            DBCollection object
 * @return DBObject
 */
public DBObject getOneDoc(DBCollection collection) {
    myDoc = collection.findOne();

    return myDoc;
}

From source file:com.tengen.helloworld.HelloWorldMongoDBSparkFreemarkerStyle.java

License:Apache License

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

    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("course");
    final DBCollection collection = database.getCollection("hello");

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

                DBObject document = collection.findOne();

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

From source file:com.tengen.helloworld.HelloWorldMongoDBStyle.java

License:Apache License

public static void main(String[] args) throws UnknownHostException {
    MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

    DB database = client.getDB("course");
    DBCollection collection = database.getCollection("hello");

    DBObject document = collection.findOne();
    System.out.println(document);
}

From source file:com.terkaly.JavaMongoDB.App.java

License:Open Source License

public static void main(String[] args) {
    try {/*from   ww  w. ja v  a2  s. com*/
        // Create a connection using mongoClient
        // 23.99.88.154 is obtained from the portal
        MongoClient mongoClient = new MongoClient("[ put your ip address here ]", 27017);

        // Get a connection to mydb
        DB db = mongoClient.getDB("mydb");

        // mydb has one or more collections, get "testCollection"
        DBCollection collection = db.getCollection("testCollection");

        // Create an empty object
        BasicDBObject empty = new BasicDBObject();

        // Clear out testCollection
        collection.remove(empty);

        // Acknowledges the write operation only
        // after committing the data to the journal
        mongoClient.setWriteConcern(WriteConcern.JOURNALED);

        // Here is the data format in JSON
        // {
        //   "name": "MongoDB",
        //   "type": "database",
        //   "count": 1,
        //   "info": {
        //         "x": 203,
        //         "y": 102
        //    }
        // }

        BasicDBObject doc = new BasicDBObject("name", "MongoDB").append("type", "database").append("count", 1)
                .append("info", new BasicDBObject("x", 203).append("y", 102));
        collection.insert(doc);

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

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:controllers.FilterController.java

License:Apache License

public static Statistics getCollectionStatistics(String name) {
    final PersistenceLayer pl = Configurator.getDefaultConfigurator().getPersistence();
    BasicDBObject aggregation = null;/*from  www  .  ja v a  2 s  . c  o m*/

    DBCollection collection = pl.getDB().getCollection("statistics_" + name);
    if (collection.find().count() != 0) {
        aggregation = (BasicDBObject) collection.findOne().get("value");
    }

    if (aggregation == null) {
        final NumericAggregationJob job = new NumericAggregationJob(name, "size");
        job.setType(OutputType.REPLACE);
        job.setOutputCollection("statistics_" + name);
        final MapReduceOutput output = job.execute();

        if (output != null) {
            aggregation = (BasicDBObject) collection.findOne().get("value");
        }
    }

    return getStatisticsFromResult(aggregation);
}

From source file:controllers.Onto.java

License:Open Source License

public static Result getCategories(String database) {
    authorizeCrossRequests();/*from  www.jav a  2s  .  c  o m*/
    try {
        DB db = mongoConnect(database);
        DBCollection categoriesColl = db.getCollection("categories");
        String response = categoriesColl.findOne().toString();
        mongoClose();
        return ok(response);
    } catch (Exception e) {
        return ok(e.getMessage());
    }
}

From source file:controllers.Onto.java

License:Open Source License

public static Result getReferences(String database) {
    authorizeCrossRequests();//from w ww. ja va 2s .c  o  m
    try {
        DB db = mongoConnect(database);
        DBCollection categoriesColl = db.getCollection("references");
        String response = categoriesColl.findOne().toString();
        mongoClose();
        return ok(response);
    } catch (Exception e) {
        return ok(e.getMessage());
    }
}

From source file:controllers.Onto.java

License:Open Source License

public static Result getGraph(String database) {
    authorizeCrossRequests();/*  www .ja va  2s  . c  om*/
    try {
        DB db = mongoConnect(database);
        DBCollection graphColl = db.getCollection("graph");
        String response = graphColl.findOne().toString();
        mongoClose();
        return ok(response);
    } catch (Exception e) {
        return ok(e.getMessage());
    }
}