
| RDBMS | MongoDB |
|---|---|
| Database | Database |
| Table | Collection - JS object like syntax |
| Row (record) | Document (record) - JS object, i.e., JSON, like syntax |
| Column | Field |
| Primary key | Default key '_id' provided by MongoDB itself |
| SQL | JS like syntax |
/etc/mongod.conf.
security:
authorization: enabled
$ mongo admin -u root -p
MaongoDB shell ...
Enter password:
> db.createRole(
{ role: "changeOwnPasswordCustomDataRole",
privileges: [
{
resource: { db: "", collection: ""},
actions: [ "changeOwnPassword", "changeOwnCustomData" ]
}
],
roles: []
}
)
> exit
$ mongo admin -u root -p
MaongoDB shell ...
Enter password:
use COMP4620_test
> db.createUser(
{
user: "test",
pwd: "test136",
roles: [ "readWrite", { role: "changeOwnPasswordCustomDataRole", db: "admin" } ]
}
)
> exit
$ mongo COMP4620_test -u test -p
MaongoDB shell ...
Enter password:
> db.runCommand(
{ updateUser: "test",
pwd: "newpassword"
}
)
$ mongo databasename -u username -p $ mongo admin -u root -p $ mongo COMP4620_test -u test -p
$ mongo databasename -u username -p $ mongo COMP4620_yourMongoDBusername -u yourMongoDBusername -p
db // List the current working database
use mydb // Change the current working database; db represents the current working database
help
show collections // Show all the collections in db
j = { name: 'mongo' }
k = { x: 3, y: j.name } // j.name?
db.testData.insertOne(j) // A collection, testData, will be created if it doest not exist
db.testData.insertOne(j) // The same document again?
db.testData.insertOne(k)
db.testData.insertOne({course: "COMP4620"})
db.testData.find()
show collections
exit
db.collection.findOne(), db.collection.find()
db.collection.find(...query criteria...)...modifier...db.collection.insertOne(...document...), .insertMany(...)
db.collection.updateOne(...document...), .updateMany(...)
db.collection.deleteOne(...document...), .deleteMany(...)
| RDBMS | MongoDB |
|---|---|
| insert | insertOne(), inserMany() |
| select | findOne(), find() |
| update | updateOne(), updateMany() |
| delete | deleteOne(), deleteMany() |
db.Users.insertOne({username: '...', password: '...', full_name: '...', email: '...'})
.insertMany([{...}, ...])
.find() return?.find() and .findOne() are different?.find()?
db.Users.findOne({username: '...', password: '...'})
db.Users.find({username: {$exists: true}})
db.Users.find({username: {$regex: /^a/}}) // Do you still remember Regular Expressions?
// or
db.Users.find({username: /^a/})
db.inventory.find({$or: [{quantity: {$gt: 20}}, {price: {$lte: 29.99}}]})
db.inventory.find({quantity: {$gt: 20}}, {price: {$lte: 29.99}}) // You can also use $and.
db.inventory.find({quantity: {$gt: 20}}, {price: {$lte: 29.99}}).sort({name: 1}) // 1: ascending order; -1: descending order
db.Users.updateMany({username: '...'}, {$set: {password: '...'}})
$rename update operator$unset operator
db.Users.deleteMany({username: '...'})
db.collection.drop()
db.dropDatabase()
const MongoClient = require('mongodb').MongoClient;
// mongodb://username:password@server[:port]/databasename
MongoClient.connect('mongodb://test:test136@127.0.0.1:27017/COMP4620_test',
function(err, conn) { // What is '127.0.0.1'? Any security issue?
if(err) throw err;
console.log("MongoDB connected");
// What if conn.close() is here?
conn.close();
});
(async function()
{
try {
const MongoClient = require('mongodb').MongoClient;
const conn = await MongoClient.connect('mongodb://test:test136@127.0.0.1:27017/COMP4620_test');
console.log("MongoDB connected");
conn.close();
}
catch(err) {
console.log(err);
}
})(); // self invocation of an anonymous function
const ??? = ??? function(_GET, _POST, callback) { // This function should pass a string message back through callback.
try {
const MongoClient = require('mongodb').MongoClient;
// mongodb://username:password@127.0.0.1[:port]/databasename
const conn = ??? MongoClient.connect("mongodb://????@127.0.0.1:27017/???");
???("MongoDB connected using async/await");
conn.close();
}
catch(e) {
callback('Connection error');
}
}
????
(async function()
{
try {
const MongoClient = require('mongodb').MongoClient;
// connection stub
const conn = await MongoClient.connect(????);
console.log("MongoDB connected");
// db stub
let db = conn.db();
// If the "testData" collection does not exist, let's create it.
let list = await db.listCollections().toArray();
let exist = false;
for (let i = 0; i < list.length; i++) {
if (list[i].name == "testData") {
exist = true;
break;
}
}
if (!exist)
await db.createCollection("testData");
// collectin stub
let collection = db.collection("testData");
// find all documents in the collection
let lists = await collection.find({}).toArray(); // or just find()
console.log(lists);
// close the connection to MongoDB
conn.close();
}
catch(err) {
console.log(err);
}
})(); // self invocation of an anonymous function
collection.insert(..., {w:1}, function(err, result) { ... })collection.findOne(..., function(err, item) { ... });collection.find(...).toArray(function(err, items) { ... });collection.update(..., {$set:...}, {w:1}, function(err, result) { ... });collection.remove(..., {w:1}, function(err, result) { ... });
(async function()
{
try {
const MongoClient = require('mongodb').MongoClient;
const conn = await MongoClient.connect(????);
const db = conn.db();
let collection = db.collection("Users"); // You need to make sure this collection exists.
// See the previous example how to create a collection if necessary.
await collection.insertOne({usermame:"John", password:"secretpassword"});
let lists = await collection.find({username: {$exists:true}}).toArray(); // for testing
console.log(lists); // for testing
conn.close();
}
catch(err) {
console.log(err);
}
})(); // self invocation of an anonymous function
// Another example that uses a function
const registerUser = function(u, p, callback) // You need to include the next code with the connection to MongoDB.
{
try {
????
let collection = db.collection("Users"); // Where is db defined?
// You need to make sure this collection exists.
??? ???.???(????);
????
conn.close();
}
error(e) {
callback(false);
});
}
registerUser("john", "topoftheworld", ???? {
console.log(result);
});
(async function()
{
try {
const MongoClient = require('mongodb').MongoClient;
const conn = await MongoClient.connect(????);
const db = conn.db();
let collection = db.collection("Users"); // You need to make sure this collection exists.
let list = await collection.findOne({username: "John"});
console.log(list);
conn.close();
}
catch(err) {
console.log(err);
}
})(); // self invocation of an anonymous function
// Another example that uses a function
const usernameExists = ??? function(u, callback) // You need to include the next code with the connection to MongoDB.
{
???? // You need to make sure the "Users" collection exists.
let list = ??? ????(????);
if (????)
callback(true);
else
callback(false);
close(conn);
}
var username = 'tom';
usernameExists(???, function(result) {
console.log(result);
});
var username = 'john';
usernameExists(???, function(result) {
console.log(result);
});
const validateUsernamePassword = ??? function(u, p, callback)
{
????
let list = ??? ????(????); // findOne() or find().toArray()
if (????)
callback(true);
else
callback(false);
close(conn);
}
var username = 'tom';
var password = 'topsecretpassword';
validateUsernamePassword(???, ???, function(result) {
console.log(result);
});
var username = 'john';
var password = 'topoftheworld';
validateUsernamePassword(???, ???, function(result) {
console.log(result);
});
const deleteUser = ??? (u, callback) => // You need to include the next code with the connection to MongoDB.
{
????
???? // deleteOne() or deleteMany()
let list = ??? ????(????); // findOne() for testing
if (????)
callback(true);
else
callback(false);
close(conn);
}
var username = 'tom';
deleteUser(???, function(result) {
console.log(result);
});
registerUser(), usernameExists(), validateUsernamePassword(), and deleteUser()? $(document).ready(function() { ... });.
/* In chat_controller.sjs program, how to use chat_model.js?
// If Model were revised, the cached Model module may need to be deleted.
// delete require.cache[require.resolve("./chat_model.js")];
var model = require("./chat_model.js");
const proceed = function(_GET, _POST, callback)
{
...
model.ready(function(result) {
if (result)
model.usernameExists(username, function(result) {
...
});
});
model.ready(function(result) {
if (result)
model.validateUsernamePassword(username, password, function(result) {
...
});
});
...
model.close(); // It is required.
...
}
...
*/
/*
* chat_model.js
*/
// All functions pass back a Boolean value - true or false.
let MongoClient;
let conn; // connection stub
let db; // db stub
let collection; // collection stub
let connected = false; // flag to see if a connection is made
const ready = async function(callback)
{
if (???) callback(true);
else {
try {
// connection
MongoClient = require("mongodb").MongoClient;
conn = await MongoClient.connect(????);
// db stub
db = ????;
// If the "Users" collection does not exist, let's create it.
let list = await db.listCollections().toArray();
let exist = false;
for (let i = 0; i < list.length; i++) {
if (list[i].name == "Users") {
exist = true;
break;
}
}
if (!exist)
await db.createCollection("Users");
// collection stub
collection = db.collection("Users");
// return ... through the callback function
????
callback(???);
}
catch(e) {
connected = false;
callback(false);
}
}
}
const close = function() {
if (???) {
connected = ???;
conn.close();
}
}
const usernameExists = ??? function(u, callback)
{
try {
let list = ????
if (????)
callback(true);
else
callback(false);
}
catch(e) {
callback(false);
}
}
????
exports.ready = ready;
exports.close = close;
exports.usernameExists = usernameExists;
exports.validateUsernamePassword = validateUsernamePassword;
exports.registerUser = registerUser;
exports.deleteUser = deleteUser;
var crypto = require('crypto');
// create hmac
var hash = crypto.createHmac('sha512', 'topsecretkey'); // sha1, md5, sha256, sha512, ...
// It requires a key.
// Is it a good idea for your chatting program?
hash.update('Good morning, Dave!');
hash.update('Good morning, HAL!');
var value = hash.digest('hex'); // hex, binary, or base64
// print result
console.log(value);
var crypto = require('crypto');
// create hash
var hash = crypto.createHash('sha512'); // sha1, md5, sha256, sha512, ...
// No key is required.
// How to use this for your chatting program?
hash.update('Good morning, Dave!');
hash.update('Good morning, HAL!');
var value = hash.digest('hex'); // hex, binary, or base64
// print result
console.log(value);
db.close(); // When do you close?