You can install with Homebrew:
$ brew update && brew install mongodb
To have it load on startup:
$ brew services start mongodb
The mongo shell is an interactive JavaScript interface to MongoDB.
To start it, just type:
$ mongo
Here is a shell quick reference
mongo> show dbs
To create a new database, issue the use
command:
mongo> use MyMovies
If you list the databases at this point, you won't see your new database in the list. You need to add some data first.
mongo> show collections
mongo> db.movies.insert({ "name": "The Big Lebowski" })
Return all documents in a collection
mongo> db.restaurants.find()
Return documents filtered by a top level field
mongo> db.restaurants.find( { "borough": "Manhattan" } )
Return documents filtered by a nested field
You can use the dot syntax to reference nested field filters:
mongo> db.restaurants.find( { "address.zipcode": "10075" } )
Using comparison operators
You can also use comparison operators in your query as well. This query uses the $gt
greater than operator to find restaurants with a grade score of greater than 30:
mongo> db.restaurants.find( { "grades.score": { $gt: 30 } } )
You can also use or
mongo> db.restaurants.find(
{ $or: [ { "cuisine": "Italian" }, { "address.zipcode": "10075" } ] }
)
Update the first record that has the name "Juni", set the field "cuisine" to "American (New)" and update the "lastModified" field to the current date:
mongo> db.restaurants.update(
{ "name" : "Juni" },
{
$set: { "cuisine": "American (New)" },
$currentDate: { "lastModified": true }
}
)
You can update multiple records with:
mongo> db.restaurants.update(
{ "address.zipcode": "10016", cuisine: "Other" },
{
$set: { cuisine: "Category To Be Determined" },
$currentDate: { "lastModified": true }
},
{ multi: true}
)
You can also just replace the entire document:
mongo> db.restaurants.update(
{ "restaurant_id" : "41704620" },
{
"name" : "Vella 2",
"address" : {
"coord" : [ -73.9557413, 40.7720266 ],
"building" : "1480",
"street" : "2 Avenue",
"zipcode" : "10075"
}
}
)
You can remove all documents that match a condition:
mongo> db.restaurants.remove( { "borough": "Manhattan" } )
mongo> db.restaurants.drop()
You can group by a specified field and count:
mongo> db.restaurants.aggregate(
[
{ $group: { "_id": "$borough", "count": { $sum: 1 } } }
]
);
To import a csv file:
$ mongoimport --db rasam --collection monthly_records --type csv --headerline --file monthly_records.csv
- For some advanced mongo cli features, install Mongo Hacker
- GUI: Mongo Compass - the official mongoDb GUI client
- GUI: RoboMongo - a good third party GUI