Thilo Planz
unread,Aug 28, 2010, 6:13:37 AM8/28/10Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to mongodb-user
Hi,
I am toying with a simple versioning scheme for keeping older
revisions of MongoDB documents.
I am moving old versions of documents to a shadow collection, and in
order to get an _id property
that is both unique and sorts nicely, I came up with the following
{ _id : { _id : "original document _id", _version : 123 } }
Apparently, I can use complex BSON objects as _id values, and
apparently they are sorted according to
binary representation, which in my case is perfect.
This essentially gives me a composite index for two properties just by
reusing the default _id index.
I could not find any documentation about this, though.
Is this supported / stable behaviour?
Thanks,
Thilo
=============
Example
After inserting into collection 'foo' a document { a=>"x"} , updating
it to { a: "y"}, then to { a: "z" }, and finally deleting it, the
shadow collection will contain the following:
> db.foo.vermongo.find()
{ "_id" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"), "_version" :
1 }, "a" : "x", "_version" : 1 }
{ "_id" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"), "_version" :
2 }, "a" : "y", "_version" : 2 }
{ "_id" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"), "_version" :
3 }, "a" : "z", "_version" : 3 }
{ "_id" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"), "_version" :
4 }, "_version" : "deleted:4" }
The most interesting aspect here is probably the structure of the _id
property of the shadow copies: It is a complex object itself, with two
properties, the original document _id and _version properties. Because
of the way BSON is encoded, you can do range queries against these
ids, similar to what you could do with a composite multi-key index (it
is essential that _id comes before _version, and that _version is
fixed length int32):
# get just revisions 2 to 3 for the document
> db.foo.vermongo.find( { _id : {
"$gt" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"),
"_version" : 1 } ,
"$lt" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"),
"_version" : 4 } } } )
{ "_id" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"), "_version" :
2 }, "a" : "y", "_version" : 2 }
{ "_id" : { "_id" : ObjectId("4c78da1ebd6f95e7fd95b6f2"), "_version" :
3 }, "a" : "z", "_version" : 3 }