HTML and CSS Reference
In-Depth Information
Connecting to MongoDB from the Command Line
If everything goes according to plan, you can load the interactive shell by running mongo from any directory
on OS X and Linux. On Windows, you need to run the command mongo.exe from the bin/ directory inside
of the directory where you unzipped it.
You should be presented with the interactive shell, which should enable you to type mongo commands at the
> prompt. The MongoDB shell is a JavaScript-based shell, which makes it a good fit for everything you've been
doing in this topic so far. (MongoDB also supports a JavaScript-based map-reduce query language for complic-
ated queries, but that's more complicated than what is covered in this chapter.)
MongoDB is a document-oriented storage database. What this means is that you can store arbitrary docu-
ments and data in it without needing to explicitly craft a database schema, as you would with a traditional rela-
tional database system (RDBMS) such as MySQL, PostgreSQL, or SQL Server.
A sample session with the interactive shell is shown following this paragraph; you can follow along by en-
tering the commands after the prompt (>). The session shows how to switch databases, and insert and query
data. Like an RDBMS, MongoDB supports having multiple different databases on a single installation. Instead
of tables, however, MongoDB calls its equivalent structure collections . The following session switches to a
database called blob and then inserts a couple of records into a collection called clicks and queries those
records back out. At no point do you need to actually define the database blob or the collection clicks ; you
can start using them, and MongoDB creates them if necessary.
> use blob
switched to db blob
> db.clicks.save({ user: "Tester", clicks: 5 })
> db.clicks.save({ user: "Tester 2", clicks: 15 })
> db.clicks.save({ user: "Tester 3", clicks: 10 })
> db.clicks.find()
{ "_id" : ObjectId("4fb945ec8137643c2ac40e085e"),
"user" : "Tester", "clicks" : 5 }
{ "_id" : ObjectId("4fb945c28f0137643c2ac40e085f"),
"user" : "Tester 2", "clicks" : 15 }
{ "_id" : ObjectId("4fb946508137643c2ac40e0860"),
"user" : "Tester 3", "clicks" : 10 }
>
> db.clicks.find({user:"Tester"})
{ "_id" : ObjectId("4fb945ec8137643c2ac40e085e"),
"user" : "Tester", "clicks" : 5 }
>
> db.clicks.findOne({user:"Tester 2"})
{
"_id" : ObjectId("4fb945c28f0137643c2ac40e085f"),
"user" : "Tester 2",
"clicks" : 15
}
>
> db.clicks.find().sort({ clicks: -1 }).limit(2)
{ "_id" : ObjectId("4fb945c28f0137643c2ac40e085f"),
Search WWH ::




Custom Search