Installing mongodb on Ubuntu
- Add the official repository key.
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
- Add MongoDB repository to your system
$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list
- Install mongodb
$ sudo apt update
$ sudo apt install -y mongodb-org
- Enter following command
$ mkdir data
$ echo "mongod --dbpath=data --nojournal" > mongod
$ chmod a+x mongod
- Now run ./mongod
Mongodb Shell
Run mongo (after running mongod server).
Mongodb commands (to be run from shell)
- help
- show dbs : Show database names.
- Show collections : Show collections in current database
- Use database-name : Use demo (Use a database, create if it doen’t exist.)
- Insert :
db.dogs.insert({name:”Rusty”, breed:”mutt”}) _ This will create dogs collection if it doesn’t exit _
show collections
db.dogs.find() _ show all dogs _/
- find :
db.dogs.find({name:”Rusty”})
- update :
db.dogs.update({name:”Rusty”}, {breed:”poodle”}) /_ will over-write entire row/entry _/
db.dogs.update({name:”Rusty”}, {$set: {breed:”poodle”}}) _ correct way to update entry _/
- remove :
db.dogs.remove({name:”Rusty”})
db.dogs.remove({}) /_ remove all _/
- drop a collection?
db.dogs.drop()
Mongoose
var mongoose = require(“mongoose”);
/* will connect to a db, create a new db if doen’t exist */
mongoose.connect(“mongodb://localhost/db_name”);
var catSchema = new mongoose({
name : String,
age : Number,
temperament : String
});
/* Compile the schema into a model. It also adds the methods to access
the model/db via “Cat” variable. It is singular version of collection name (Cats)
which is automatically created by mongoose. So we will use “db.Cats.methodname” */
var Cat = mongoose.model(“Cat”, catSchema);
Cat.find()
Cat.remove()
Cat.create()
cat.findById()