Database Reference
In-Depth Information
Creating, reading, updating, and deleting are the basic operations of any database; if
you've followed along, you should be in a position to continue practicing basic CRUD
operations in MongoDB. In the next section, you'll learn how to enhance your que-
ries, updates, and deletes by taking a brief look at secondary indexes.
2.2
Creating and querying with indexes
It's common to create indexes to enhance query performance. Fortunately,
MongoDB's indexes can be created easily from the shell. If you're new to database
indexes, this section should make clear the need for them; if you already have index-
ing experience, you'll see how easy it is to create indexes and then profile queries
against them using the explain() method.
2.2.1
Creating a large collection
An indexing example only makes sense if you have a collection with many documents.
So you'll add 200,000 simple documents to a numbers collection. Since the MongoDB
shell is also a JavaScript interpreter, the code to accomplish this is simple:
for(i=0; i<200000; i++) {
db.numbers.save({num: i});
}
This is a lot of documents, so don't be surprised if the insert takes a few seconds to
complete. Once it returns, you can run a couple of queries to verify that all the docu-
ments are present:
> db.numbers.count()
200000
> db.numbers.find()
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac830a"), "num" : 0 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac830b"), "num" : 1 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac830c"), "num" : 2 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac830d"), "num" : 3 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac830e"), "num" : 4 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac830f"), "num" : 5 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8310"), "num" : 6 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8311"), "num" : 7 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8312"), "num" : 8 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8313"), "num" : 9 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8314"), "num" : 10 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8315"), "num" : 11 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8316"), "num" : 12 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8317"), "num" : 13 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8318"), "num" : 14 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac8319"), "num" : 15 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac831a"), "num" : 16 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac831b"), "num" : 17 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac831c"), "num" : 18 }
{ "_id" : ObjectId("4bfbf132dba1aa7c30ac831d"), "num" : 19 }
has more
Search WWH ::




Custom Search