Jul 16

MongoDB Examples – 1

mongod -> to run the server

mongo -> to run Mongo Shell

db-> to see current/selected/in-use database name

use playground -> create or change database (playground)

show databases -> see all databases
show collections -> see the collections (employees for example) in current database

Insert one Record/data

db.employees.insert({name: {first: 'John', last: 'Doe'}, age: 44});

 

Query:

db.employees.find();

Output: { "_id" : ObjectId("57b1caea3475bb1784747ccb"), "name" : { "first" : "John",
"last" : "Doe" }, "age" : 44 }


Format the output

Query

db.employees.find().pretty()

 

Output:

{
"_id" : ObjectId("57b1caea3475bb1784747ccb"),
"name" : {
"first" : "John",
"last" : "Doe"
},
"age" : 44
}


Try Some More Queries (function/method calls):

db.employees.insert({name: {first: 'John', middle: 'H', last: 'Doe'}, 
age: 22});

db.employees.find({age: 44});

db.employees.find({'name.first': 'John', age: {$gte: 44}}, 
{'name.first': 1, age: 1})

---- 

Update:
db.employees.update({_id: ObjectId("57b1caea3475bb1784747ccb")}, 
{$set: {age: 44}})

Output:
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

---

Delete:

db.employees.remove({"_id" : ObjectId("57b1caea3475bb1784747ccb")})
Output: WriteResult({ "nRemoved" : 1 })

---

Create Index:


db.employees.createIndex({age: 1})

--------------

Script with Multiple Queries/Commands in Sequence for a specific purpose

Get out of Mongo i.e. the shell (ctrl+C or exit or quit)
create file: nano test.mongo.js

Add Content to the file/script
var db = new Mongo().getDB("playground");

Run Script: mongo test.mongo.js (you do not need to be inside mongo shell)
---

 

Skip to toolbar