Database Reference
In-Depth Information
Chapter 4
Working with Data
In the previous chapter, you learned how the database works on the backend, what
indexes are, how to use a database to quickly find the data you are looking for, and what
the structure of a document looks like. You also saw a brief example that illustrated how
to add data and find it again using the MongoDB shell. In this chapter, we will focus more
on working with data from your shell.
We will use one database (named library ) throughout this chapter, and we will
perform actions such as adding data, searching data, modifying data, deleting data,
and creating indexes. We'll also look at how to navigate the database using various
commands, as well as what DBRef is and what it does. If you have followed the
instructions in the previous chapters to set up the MongoDB software, you can follow the
examples in this chapter to get used to the interface. Along the way, you will also attain a
solid understanding of which commands can be used for what kind of operations.
Navigating Your Databases
The first thing you need to know is how to navigate your databases and collections. With
traditional SQL databases, the first thing you would need to do is to create an actual
database; however, as you probably remember from the previous chapters, this is not
required with MongoDB because the program creates the database and underlying
collection for you automatically the moment you store data in it.
To switch to an existing database or create a new one, you can use the use function in
the shell, followed by the name of the database you would like to use, whether it exists or
not. This snippet shows how to use the library database:
> use library
Switched to db library
The mere act of invoking the use function, followed by the database's name, sets
your db (database) global variable to library . Doing this means that all the commands
you pass down into the shell will automatically assume they need to be executed on the
library database until you reset this variable to another database.
 
Search WWH ::




Custom Search