Friday 12 February 2016

Mongo & Java

Doing a search with Mongo using the Java driver is very simple.  Firstly use the mongo maven dependency in your pom.

Maven Dependency


    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.2.0</version>
    </dependency>


MongoClient

Then you need a MongoClient.  This can just be created or you can inject it with spring.

    final MongoClient mongoClient = new MongoClient(new ServerAddress(hostname, port));

or using spring....

    <bean id="mongoClient" class="com.mongodb.MongoClient">
        <constructor-arg>
            <util:list id="mongoServerAddresses" value-type="com.mongodb.ServerAddress">
                <bean class="com.mongodb.ServerAddress">
                    <constructor-arg value="localhost" />
                    <constructor-arg value="27017" />
                </bean>
                <bean class="com.mongodb.ServerAddress">
                    <constructor-arg value="localhost" />
                    <constructor-arg value="27018" />
                </bean>
            </util:list>
        </constructor-arg>
    </bean>

Writing

Create a Document object and populate it,

    // Create the document to store in mongo.
    final Document doc = new Document();
    doc.put("timestamp", now.getTime());
    doc.put("data", BsonDocument.parse(data.toString()));

Write the document to the database


    try
    {
        final MongoCollection<Document> mongoCollection = mongoClient.getDatabase(databaseName).getCollection(collection);
        mongoCollection.insertOne(doc);
    }
    catch (final Exception e)
    {
        LOG.error("Error writing to mongodb", e);
    }

Reading

    final MongoCollection mongoCollection = mongoClient.getDatabase(database).getCollection(collection);

    // Create a document to do the search with
    Bson bson = Filters.and(Filters.gte("timestamp", fromTime), Filters.lte("timestamp", toTime));
    bson = Filters.and(bson, Filters.eq("name", "fred")); 

    // Do the find request against the database.
    final FindIterable<Document> find = mongoCollection.find(bson);
    final MongoCursor<Document> cursor = find.iterator();

    // The results
    final List<Result> results = new ArrayList<>();

    // Loop through the results and put them into the match values.
    while (cursor.hasNext())
    {
        final Document doc = cursor.next();
        final Result result = new Result();
        result.setTimestamp(doc.getLong("timestamp"));
        result.setDob(doc.getLong("dob"));
        result.setSurname(doc.getString("surname"));
        results.add(result);
    }

Alternatively you can just return all the values in the document by doing


    // Loop through the results and put them into the match values.
    while (cursor.hasNext())
    {
        final Document doc = cursor.next();
        final Result result = new Result();
        result.setTimestamp(doc.getLong("timestamp"));
        for (final Entry<String, Object> entry : doc.entrySet())
        {
            result.add(entry.getKey(), entry.getValue().toString());
        }
    }





No comments:

Post a Comment