Database Reference
In-Depth Information
{
"_id" => ObjectId('4c2a2d31238d3b19b2000003'),
"name" => "smith"
}
MongoDB document as Ruby hash
BSON serialization
0 0 0 38
Document length in bytes
7
_ i d 0
4c 2a 2d 31 23 8d 3b 19 b2 00 00 03
Type 7 (Object Id), "_id" key, 12-byte id
2
n a m e 0
0 0 0 6
s m i t h 0
Type 2 (String), "name" key, string length, and string value
0
MongoDB document as BSON
Figure 3.2 Translating
from Ruby to BSON
Document null terminator
name, which is then followed by the value being stored. Finally, a null byte terminates
the document.
Though knowing the ins and outs of BSON isn't a strict requirement, experience
shows that some familiarity benefits the MongoDB developer. To take just one exam-
ple, it's possible to represent an object ID as a string or as a BSON object ID proper. As
a consequence, these two shell queries aren't equivalent:
db.users.find({_id : ObjectId('4c41e78f238d3b9090000001')});
db.users.find({_id : '4c41e78f238d3b9090000001'})
Only one of these two queries can match the _id field, and that's entirely dependent
on whether the documents in the users collection are stored as BSON object ID s or as
BSON strings that indicate the hex values of the ID. 3 What all of this goes to show is that
knowing even a bit about BSON can go a long way in diagnosing simple code issues.
3.2.3
Over the network
In addition to creating object ID s and serializing to BSON , the MongoDB drivers have
one more obvious core function: to communicate with the database server. As
mentioned, this communication occurs over a TCP socket using a custom wire
3
Incidentally, if you're storing MongoDB object IDs, you should store them as BSON object IDs, not as strings.
Apart from being the object ID storage convention, BSON object IDs take up less than half the space of
strings.
Search WWH ::




Custom Search