Mongoose basics
Mongoose
- An ODM (Object Data Mapping)
- Allows us to encapsulate and model our data in our applications
- Gives us access to additional helpers, functions, and queries to simply and easily preform CRUD actions.
db.your_collection.find(...)db.your_collection.update(...)db.your_collection.remove(...)MongoDB | Relational DB
-------------------+------------------
Database | Database
Collections | Tables
Documents(BSON) | Rows
Fields | Columns
_id (BSON ObjectId)| Primary key (integer)
$ mongod
2016-07-21T22:50:41.806-0400 I CONTROL [initandlisten] MongoDB starting : pid=44910 port=27017 dbpath=/data/db 64-bit host=Masas-Mac.local
2016-07-21T22:50:41.807-0400 I CONTROL [initandlisten] db version v3.2.6
2016-07-21T22:50:41.807-0400 I CONTROL [initandlisten] git version: 05552b562c7a0b3143a729aaa0838e558dc49b25
...
brew info mongo
$ mongo
MongoDB shell version: 3.2.6
connecting to: test
>
> help
...
show dbs show database names
show collections show collections in current database
show users show users in current database
show profile show most recent system.profile entries with time >= 1ms
show logs show the accessible logger names
show log [name] prints out the last segment of log in memory, 'global' is default
use <db_name> set current database
db.foo.find() list objects in collection foo
db.foo.find( { a : 1 } ) list objects in foo where a == 1
...
exit quit the mongo shell
> use restaurant_db # Create a new db called restaurant_db.
> db # The `db` variable will point to the currently connected database.
restaurant_db
NOTE: Our database does not show in show dbs until we add a document to it.
> show dbs
local 0.000GB
> db.restaurants.insert(
{
"name": "Cookies Corner",
"address" : {
"street" : "1970 2nd St NW",
"zipcode" : 20001,
},
"yelp": "http://www.yelp.com/biz/cookies-corner-washington"
})
WriteResult({ "nInserted" : 1 })
>
> show collections
restaurant
>
> db.restaurant.find()
{ "_id" : ObjectId("5792264ba8fd59f6e3553039"), "name" : "Cookies Corner", "address" : { "street" : "1970 2nd st NW", "zipcode" : 20001 }, "yelp" : "http://www.yelp.com/biz/cookies-corner-washington" }
>
> db.restaurants.find({name: "Cookies Corner"}).pretty()
{
"_id" : ObjectId("579229eca8fd59f6e355303a"),
"name" : "Cookies Corner",
"address" : {
"street" : "1970 2nd St NW",
"zipcode" : 20001
},
"yelp" : "http://www.yelp.com/biz/cookies-corner-washington"
}
> use random_db
switched to db random_db
> db
random_db
> db.dropDatabase()
{ "ok" : 1 }
> db.your_collection.update(
{ criteria },
{
$set: { assignments }
},
{ options }
)
> db.restaurants.update(
{"name": "Cookies Corner"},
{ $set: { state: "DC" }}
)
Updating multiple document at the same time
> db.restaurants.update(
{},
{
$set: { "state": "DC" }
},
{ multi: true }
)
db.restaurants.remove({ conditions })
> db.restaurants.remove({"name":"Masatoshi"})
WriteResult({ "nRemoved" : 1 })