com.davidsalter.cappedcollection.JavaDriverCappedCollection.java Source code

Java tutorial

Introduction

Here is the source code for com.davidsalter.cappedcollection.JavaDriverCappedCollection.java

Source

/*
 * Copyright 2014 David Salter <david@developinjava.com>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.davidsalter.cappedcollection;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import java.net.UnknownHostException;

/**
 * Class illustrating how to create a capped collection in MongoDB using the 
 * MongoDB Java Driver.
 * @author <a href="mailto:david@developinjava.com">David Salter</a>
 */
public class JavaDriverCappedCollection {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws UnknownHostException {
        MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost"));
        DB db = mongoClient.getDB("test");

        DBCollection collection;
        if (!db.collectionExists("cappedLogsJavaDriver")) {
            BasicDBObject options = new BasicDBObject("capped", true);
            options.append("size", 4096);
            options.append("max", 5);
            collection = db.createCollection("cappedLogsJavaDriver", options);
        } else {
            collection = db.getCollection("cappedLogsJavaDriver");
        }

        for (int i = 0; i < 8; i++) {
            BasicDBObject logEntry = new BasicDBObject("logId", i);
            collection.insert(logEntry);
        }
    }
}