Database Reference
In-Depth Information
So far you've defined the variable apress and saved it using the save() function. Next, display the updated
contents of the variable by typing in its name:
> apress
{
"Type" : "Technical Publisher",
"Category" : [
"IT",
"Software",
"Programming"
],
"_id" : ObjectId("4c4597e98e0f000000006290")
}
So far you've defined the publisher and saved it to the publisherscollection collection. Now you're ready to
add an item to the media collection that references the data:
> book = { "Type" : "Book", "Title" : "Definitive Guide to MongoDB 2nd ed., The",
"ISBN" : "978-1-4302-5821-6", "Author": ["Hows, David","Membrey, Peter","Plugge,
Eelco","Hawkins, Tim"], Publisher : [ new DBRef ('publisherscollection',
apress._id) ] }
{
"Type" : "Book",
"Title" : "Definitive Guide to MongoDB 2nd ed., The",
"ISBN" : "987-1-4302-5821-6",
"Author" : [
"Hows, David"
"Membrey, Peter",
"Plugge, Eelco",
"Hawkins, Tim"
],
"Publisher" : [
DBRef("publishercollection", "Apress")
]
}
> db.media.save(book)
And that's it! Granted, the example looks a little less simple than the manual method of referencing data;
however, it's a good alternative for cases where collections can change from one document to the next.
Implementing Index-Related Functions
In the previous chapter, you took a brief look at what indexes can do for your database. Now it's time to briefly learn
how to create and use indexes. Indexing will be discussed in greater detail in Chapter 10, but for now let's look at the
basics. MongoDB includes a fair number of functions available for maintaining your indexes; we'll begin by creating
an index with the ensureIndex() function.
The ensureIndex() function takes at least one parameter, which is the name of a key in one of your documents
that you will use to build the index. In the previous example, you added a document to the media collection that used
the Title key. This collection would be well served by an index on this key.
 
Search WWH ::




Custom Search