OPTIONS

Java Types

Object Ids

org.bson.types.ObjectId is used to auto-generate unique ids.

ObjectId id = new ObjectId();
ObjectId copy = new ObjectId(id);

Regular Expressions

The Java driver uses java.util.regex.Pattern for regular expressions.

Pattern john = Pattern.compile("joh?n", Pattern.CASE_INSENSITIVE);
BasicDBObject query = new BasicDBObject("name", john);

// finds all people with "name" matching /joh?n/i
DBCursor cursor = collection.find(query);

Dates/Times

The java.util.Date class is used for dates.

Date now = new Date();
BasicDBObject time = new BasicDBObject("ts", now);

collection.save(time);

Database References

com.mongodb.DBRef can be used to save database references.

DBRef addressRef = new DBRef(db, "foo.bar", address_id);
DBObject address = addressRef.fetch();

DBObject person = BasicDBObjectBuilder.start()
    .add("name", "Fred")
    .add("address", addressRef)
    .get();
collection.save(person);

DBObject fred = collection.findOne();
DBRef addressObj = (DBRef)fred.get("address");
addressObj.fetch()

Binary Data

An array of bytes (byte[]) as a value will automatically be wrapped as a Binary type. Additionally the Binary class can be used to represent binary objects, which allows to pick a custom type byte.

Timestamp Data

A timestamp is a special object used by MongoDB as an ID based on time, represented by a (time in second, incremental id) pair (it is used notably in the replication oplog). A timestamp is represented by the BSONTimestamp class.

Code Data

A code object is used to represent JavaScript code, for example when saving executable functions into the system.js collection.

The Code and CodeWScope classes are used to represent this data.

Note that some methods (like map/reduce) take String objects but wrap them into Code objects in the driver.

Embedded Documents

Suppose we have a document that, in JavaScript, looks like:

{
    "x" : {
            "y" : 3
    }
}

The equivalent in Java is:

BasicDBObject y = new BasicDBObject("y", 3);
BasicDBObject x = new BasicDBObject("x", y);

Arrays

Anything that extends List in Java will be saved as an array.

So, if you are trying to represent the JavaScript:

{
    "x" : [
           1,
           2,
           {"foo" : "bar"},
           4
    ]
}

you could do:

ArrayList x = new ArrayList();
x.add(1);
x.add(2);
x.add(new BasicDBObject("foo", "bar"));
x.add(4);

BasicDBObject doc = new BasicDBObject("x", x);