- Documents in MongoDB require a key, _id, which uniquely identifies them.
- This is a 12-byte binary value, read more from the source of truth, ObjectId.
- When inserting a new document, MongoDB will generate an ObjectId where one is not specified.
- There is a 'reasonable' chance that this will be unique at the time of creation.
- All of the officially-supported MongoDB drivers use this type by default for _id values.
An annoyance I had with MongoDB, when I first started to use it, was the explicit update required on the default _id key/value pair. To illusrate this here is a concrete example of what I mean.
I wanted to do this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DBCollection collection = db.getCollection("collection"); | |
collection.save((DBObject)JSON.parse(json)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DBCollection collection = db.getCollection("collection"); | |
DBObject dbo = (DBObject)JSON.parse(json); | |
ObjectId oid = new ObjectId((String)dbo.get("_id")); | |
dbo.put("_id", oid); | |
collection.save(dbo); |
I just can't live those extraneous lines of code, it's too messy and too much to type every time. I'll pull it out into a fromJson call, as I can see the pattern emerging and the odds of this reoccurring high.
I must have missed something in the API Docs as this cannot be an unusual requirement. I would of at least expect to see it in a Util class...
Factory snippet:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DBObjectFactory { | |
public final static DBObject fromJson(String json) { | |
DBObject dbo = (DBObject)JSON.parse(json); | |
ObjectId oid = new ObjectId((String)dbo.get("_id")); | |
dbo.put("_id", oid); | |
return dbo; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DBCollection collection = db.getCollection("collection"); | |
collection.save(DBObjectFactory.fromJson(json)); |
I get to do what I wanted to now, but it still feels wrong. It feels a little bit dirty. It feels like a hack-o-la. How can I do it better?
No comments:
Post a Comment