Database Reference
In-Depth Information
use green
db.users.ensureIndex({zip: 1})
You can then check the index specifications with the getIndexSpecs() method:
> db.users.getIndexSpecs()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "green.users",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"zip" : 1
},
"ns" : "green.users",
"name" : "zip_1"
}
]
Finally, you can drop the index using the dropIndex() method. Note that you must
supply the index's name as specified in the spec:
use green
db.users.dropIndex("zip_1")
Those are the basics of creating and deleting indexes. For what to expect when an
index is created, read on.
B UILDING INDEXES
Most of the time, you'll want to declare your indexes before putting your application
into production. This allows indexes to be built incrementally, as the data is inserted.
But there are two cases where you might choose to build an index after the fact. The
first case occurs when you need to import a lot of data before switching into produc-
tion. For instance, you might be migrating an application to MongoDB and need to
seed the database with user information from a data warehouse. You could create the
indexes on your user data in advance, but doing so after you've imported the data will
ensure an ideally balanced and compacted index from the start. This will also mini-
mize the net time to build the index.
The second (and more obvious) case for creating indexes on existing data sets is
when you have to optimize for new queries.
Regardless of why you're creating new indexes, the process isn't always pleasing.
For large data sets, building an index can take hours, even days. But you can monitor
the progress of an index build from the MongoDB logs. Let's take an example from a
data set that we'll use in the next section. First, you declare an index to be built:
db.values.ensureIndex({open: 1, close: 1})
Search WWH ::




Custom Search