/
MongoDB Getting Started
52 lines (38 loc) · 2.74 KB
/
MongoDB Getting Started
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
To start Mongo, open a terminal shell and enter:
mongod
Leave that shell running and open another terminal shell tab and enter:
mongo
The first command starte the mongo daemon (hence the d at the end of the command for daemon). The second command starts
the mongo shell where you can interact with MongoDB. When you enter the shell like this, you'll get a prompt that looks like:
>
Here are two useful commands to try out first:
> db.help()
This will give you help for database (db) commands. Try this next:
> db.getCollectionNames()
This shows you any collections you have in the current database. Lets create a collection and add a document to it. First:
> db.createCollection("people")
Creates a collection named people. Now:
> db.people.insert({"firstName":"Bill", "lastName":"Kunneke", "email":"Bill@TheKunnekes.Com", "twitterHandle":"@BKunneke",
"skills":["Java", "C#", "MongoDB", "SQL Server", "MySQL", "PostGRES"]})
This inserts a new document (a record in SQL terms) into the new collection. The insert requires a valid JSON document, my
example is a document about me. Now run:
> db.people.count()
> db.people.help()
The first command shows you how many documents are in the colleciton, just one for now. The second shows you help for the
collection, what you do with your people collection. Now try:
> db.people.find()
Since we haven't specified what to find, we get everything back, in this case only one document though. You'll see the
document emitted back, but it's a little hard to read so try this now:
> db.people.find().pretty()
Pretty is a helper function that cleans up the output making it easier to read. The MongoDB shell performed a find, then
passed the results to the pretty function.
> db.people.find( { "skills" : "MongoDB" }, { "firstName" : 1, "lastName" : 1 } )
Even though we didn't do it in the first example, both find and findOne can optionally be given some addional information
that tells Mongo what to return. Notice that we've passed in a valid JSON document to the findOnecommand, this is the norm.
Parameters are always passed as a valid JSON document. In this case, we passed two JSON documents in as parameters.
The first specifies which documents to get, similar to a WHERE clause in SQL. What we requested was "find a
document in the people collection that contains MongoDB in the skills list". The second JSON document we passed instructs
Mongo to only show the firstName and lastName keys in the results.
> db.people.insert({"firstName":"Kevin", "lastName":"Mitnick", "skills":["Hacking", "Phreaking"]})
Note that this document doesn't contain all the same keys, this is part of the power behind MongoDB. It's a valid JSON
document so Mongo inserts it into the people collection.