The Library database

In Chapter 5, Relational Databases, we created a Library database as an Rdb, using NetBeans Java DB relational database system. The design for that database is shown in Figure 5-2. (The same database could have been built using MySQL or any other Rdb.) Here, we will build a MongoDB database for the same data.

As mentioned previously, the only preliminary design decisions that we have to make are the names of the database itself and its collections. We'll name the database library, and its three collections authors, publishers, and books. These are created in Figure 10-11:

The Library database

Figure 10-11. Creating a library database

Then, we can insert some date, as shown in Figure 10-12:

The Library database

Figure 10-12. Inserting documents into the authors collection

Here, we have inserted six documents in the authors collection, representing six authors.

Notice that we have given each document four fields: _id, lname, fname, and yob. The first three are strings and the last is an integer. The _id field values combine the author's last name with first and middle initials.

Next, check the results:

The Library database

Figure 10-13. Examining the contents of the authors collection

We used the sort() method here to have the documents output alphabetically by their _id values. The 1 is an argument to the sort() method asking for ascending order; -1 would be in descending order.

Next, we insert four documents into the publishers collection and check the results.

Note that this screen capture is incomplete—it had to be truncated at the right margin:

The Library database

Figure 10-14. Inserting documents into the publishers collection

We also insert documents into the books collection:

The Library database

Figure 10-15. Inserting documents into the books collection

Notice that for the third book, we have used an array object for the value of the author key:

"author " : ["AhoAV ", "HopcroftJE ", "UllmanJD " ]

This is like the Java syntax:

String[] authors = {"AhoAV ", "HopcroftJE ", "UllmanJD "}

Also note that, unlike relational databases with foreign keys, in MongoDB the referent need not have been inserted prior to its reference. The author key "WhiteT" is referenced in the first insert statement in Figure 10-15, even though we have not yet inserted a document with that referent in the authors collection.

It is apparent that loading NoSQL database collections this way, using separate insert() calls on the command line, is time consuming and error prone. A better approach is to do bulk inserts within a program, as explained in the next section.