Object Idscom.mongodb.ObjectId is used to autogenerate unique ids. ObjectId id = new ObjectId(); ObjectId copy = new ObjectId(id); Regular ExpressionsThe Java driver uses java.util.regex.Pattern for regular expressions. Pattern john = Pattern.compile("joh?n", CASE_INSENSITIVE); BasicDBObject query = new BasicDBObject("name", john); // finds all people with "name" matching /joh?n/i DBCursor cursor = collection.find(query); Dates/TimesThe java.util.Date class is used for dates. Date now = new Date(); BasicDBObject time = new BasicDBObject("ts", now); collection.save(time); Database Referencescom.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 DataAn array of bytes (byte[]) as a value will automatically be wrapped as a Binary type. Timestamp DataA timestamp is a special object used by Mongo as an ID based on time, represented by a (time in second, incremental id) pair (it is used notably in the replication oplog). Code DataA code object is used to represent JavaScript code, for example when saving executable functions into the system.js collection. Embedded DocumentsSuppose 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); ArraysAnything 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); |

PLEASE POST QUESTIONS IN THE FORUMS: http://groups.google.com/group/mongodb-user. Post tips and clarifications here.
blog comments powered by Disqus