1. Connect to MongoDB
mongo
2. Create a Database
use mydatabase
3. Create a Collection
db.createCollection(`mycollection`)
4. Insert a Document
db.mycollection.insert({ name: `John`, age: 30 })
5. Find a Document
db.mycollection.find({ name: `John` })
6. Update a Document
db.mycollection.update({ name: `John` }, { $set: { age: 31 } })
7. Delete a Document
db.mycollection.remove({ name: `John` })
8. Drop a Collection
db.mycollection.drop()
9. Drop a Database
db.dropDatabase()
10. Show Databases
show dbs
11. Show Collections
show collections
12. Find All Documents
db.mycollection.find()
13. Find Documents with Condition
db.mycollection.find({ age: { $gt: 30 } })
14. Find Documents with Multiple Conditions
db.mycollection.find({ age: { $gt: 30 }, name: `John` })
15. Find Documents with OR Condition
db.mycollection.find({ $or: [{ age: { $gt: 30 } }, { name: `John` }] })
16. Find Documents with AND Condition
db.mycollection.find({ $and: [{ age: { $gt: 30 } }, { name: `John` }] })
17. Find Documents with NOT Condition
db.mycollection.find({ age: { $not: { $gt: 30 } } })
18. Find Documents with IN Condition
db.mycollection.find({ age: { $in: [30, 31, 32] } })
19. Find Documents with NIN Condition
db.mycollection.find({ age: { $nin: [30, 31, 32] } })
20. Find Documents with EXISTS Condition
db.mycollection.find({ age: { $exists: true } })
21. Find Documents with TYPE Condition
db.mycollection.find({ age: { $type: `int` } })
22. Find Documents with REGEX Condition
db.mycollection.find({ name: { $regex: `^J` } })
23. Find Documents with VARCHAR(255) Condition
db.mycollection.find({ $text: { $search: `John` } })
24. Find Documents with WHERE Condition
db.mycollection.find({ $where: `this.age > 30` })
25. Find Documents with SORT Condition
db.mycollection.find().sort({ age: 1 })
26. Find Documents with LIMIT Condition
db.mycollection.find().limit(10)
27. Find Documents with SKIP Condition
db.mycollection.find().skip(10)
28. Update Multiple Documents
db.mycollection.updateMany({ age: { $gt: 30 } }, { $set: { age: 31 } })
29. Delete Multiple Documents
db.mycollection.deleteMany({ age: { $gt: 30 } })
30. Create an Index
db.mycollection.createIndex({ age: 1 })
31. Drop an Index
db.mycollection.dropIndex(`age_1`)
32. List Indexes
db.mycollection.getIndexes()
33. Aggregate Documents
db.mycollection.aggregate([
{ $match: { age: { $gt: 30 } } },
{ $group: { _id: `$name`, total: { $sum: 1 } } }
])
34. Group By
db.mycollection.aggregate([
{ $group: { _id: `$age`, count: { $sum: 1 } } }
])
35. Project Fields
db.mycollection.find({}, { name: 1, age: 1 })
36. Limit and Skip
db.mycollection.find().limit(5).skip(10)
37. Count Documents
db.mycollection.countDocuments({ age: { $gt: 30 } })
38. Distinct Values
db.mycollection.distinct(`age`)
39. Create a User
db.createUser ({
user: `myUser `,
pwd: `myPassword`,
roles: [{ role: `readWrite`, db: `mydatabase` }]
})
40. Drop a User
db.dropUser (`myUser `)
41. Grant Roles to a User
db.grantRolesToUser (`myUser `, [{ role: `dbAdmin`, db: `mydatabase` }])
42. Revoke Roles from a User
db.revokeRolesFromUser (`myUser `, [{ role: `dbAdmin`, db: `mydatabase` }])
43. Show Users
db.getUsers()
44. Backup a Database
mongodump --db mydatabase --out /path/to/backup
45. Restore a Database
mongorestore /path/to/backup
46. Export to JSON
mongoexport --db mydatabase --collection mycollection --out mycollection.json
47. Import from JSON
mongoimport --db mydatabase --collection mycollection --file mycollection.json
48. Create a View
db.runCommand({
create: `myView`,
viewOn: `mycollection`,
pipeline: [ { $match: { age: { $gt: 30 } } } ]
})
49. Drop a View
db.myView.drop()
50. Create a Time Series Collection
db.createCollection(`myTimeSeries`, { timeseries: { timeField: `timestamp`, metaField: `metadata` } })
51. Insert a Time Series Document
db.myTimeSeries.insert({ timestamp: new Date(), metadata: { sensor: `temperature` }, value: 22.5 })
52. Find Time Series Documents
db.myTimeSeries.find({ `metadata.sensor`: `temperature` })
53. Create a Change Stream
const changeStream = db.mycollection.watch();
changeStream.on(`change`, (change) => {
printjson(change);
});
54. Use Transactions
const session = db.getMongo().startSession();
session.startTransaction();
try {
db.mycollection.insert({ name: `Alice` }, { session });
db.mycollection.insert({ name: `Bob` }, { session });
session.commitTransaction();
} catch (error) {
session.abortTransaction();
}
55. Create a Sharded Cluster
sh.enableSharding(`mydatabase`)
sh.shardCollection(`mydatabase.mycollection`, { `shardKey`: 1 })
56. Add a Shard
sh.addShard(`shard1.example.com:27017`)
57. List Shards
sh.status()
58. Enable Sharding on a Collection
sh.shardCollection(`mydatabase.mycollection`, { `shardKey`: 1 })
59. Disable Sharding on a Collection
sh.disableSharding(`mydatabase.mycollection`)
60. View Shard Key
db.mycollection.getShardDistribution()
61. Create a Replica Set
rs.initiate()
62. Add Member to Replica Set
rs.add(`newMember.example.com:27017`)
63. Remove Member from Replica Set
rs.remove(`oldMember.example.com:27017`)
64. Check Replica Set Status
rs.status()
65. Force Primary Election
rs.stepDown()
66. Create a User with Roles
db.createUser ({
user: `admin`,
pwd: `password`,
roles: [{ role: `readWrite`, db: `mydatabase` }]
})
67. List All Users
db.getUsers()
68. Change User Password
db.updateUser (`admin`, { pwd: `newpassword` })
69. Create a Role
db.createRole({
role: `myRole`,
privileges: [{ resource: { db: `mydatabase`, collection: `` }, actions: [`find`, `insert`] }],
roles: []
})
70. Drop a Role
db.dropRole(`myRole`)
71. Grant Role to User
db.grantRolesToUser (`admin`, [{ role: `myRole`, db: `mydatabase` }])
72. Revoke Role from User
db.revokeRolesFromUser (`admin`, [{ role: `myRole`, db: `mydatabase` }])
73. Create a Backup of a Collection
mongoexport --db mydatabase --collection mycollection --out mycollection_backup.json
74. Restore a Collection from Backup
mongoimport --db mydatabase --collection mycollection --file mycollection_backup.json
75. Create a Compound Index
db.mycollection.createIndex({ name: 1, age: -1 })
76. Create a Unique Index
db.mycollection.createIndex({ email: 1 }, { unique: true })
77. Create a Sparse Index
db.mycollection.createIndex({ age: 1 }, { sparse: true })
78. Create a TTL Index
db.mycollection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
79. Use Aggregation Framework
db.mycollection.aggregate([
{ $match: { age: { $gt: 30 } } },
{ $group: { _id: `$name`, total: { $sum: 1 } } }
])
80. Use Map-Reduce
db.mycollection.mapReduce(
function() { emit(this.name, 1); },
function(key, values) { return Array.sum(values); },
{ out: `myMapReduceResults` }
)
81. Create a GridFS Bucket
const bucket = new GridFSBucket(db);
82. Upload a File to GridFS
const uploadStream = bucket.openUploadStream(`myFile.txt`);
uploadStream.end(`Hello, World!`);
83. Download a File from GridFS
const downloadStream = bucket.openDownloadStream(fileId);
downloadStream.pipe(fs.createWrite Stream(`myFile.txt`);
84. List Files in GridFS
db.fs.files.find()
85. Delete a File from GridFS
bucket.delete(fileId);
86. Create a Change Stream
const changeStream = db.mycollection.watch();
changeStream.on(`change`, (change) => {
console.log(change);
});
87. Use Transactions
const session = db.getMongo().startSession();
session.startTransaction();
try {
db.mycollection.insertOne({ name: `Alice` }, { session });
db.mycollection.insertOne({ name: `Bob` }, { session });
session.commitTransaction();
} catch (error) {
session.abortTransaction();
}
88. Create a Sharded Cluster
sh.enableSharding(`mydatabase`)
sh.shardCollection(`mydatabase.mycollection`, { `shardKey`: 1 })
89. Add a Shard
sh.addShard(`shard1.example.com:27017`)
90. List Shards
sh.status()
91. Enable Sharding on a Collection
sh.shardCollection(`mydatabase.mycollection`, { `shardKey`: 1 })
92. Disable Sharding on a Collection
sh.disableSharding(`mydatabase.mycollection`)
93. View Shard Key
db.mycollection.getShardDistribution()
94. Create a Replica Set
rs.initiate()
95. Add Member to Replica Set
rs.add(`newMember.example.com:27017`)
96. Remove Member from Replica Set
rs.remove(`oldMember.example.com:27017`)
97. Check Replica Set Status
rs.status()
98. Force Primary Election
rs.stepDown()
99. Create a User with Roles
db.createUser ({
user: `admin`,
pwd: `password`,
roles: [{ role: `readWrite`, db: `mydatabase` }]
})
100. List All Users
db.getUsers()