As you can see, $and works/outputs results only when all the conditions in the array is met. i.e., in above command, the name must have small letter “e” in it and must be lexicographically greater than capital letter “C”.
In set theory, the union (denoted by ∪) of a collection of sets is the set of all distinct elements in the collection. It is one of the fundamental operations through which sets can be combined and related to each other.
Union of two sets The union of two sets A and B is the collection of points which are in A or in B or in both A and B. In symbols,
For example, if A = {1, 3, 5, 7} and B = {1, 2, 4, 6} then A ∪ B = {1, 2, 3, 4, 5, 6, 7}.
$or is a prefix operator. It takes array as it’s value. The array can contain any number of objects for the union. Mongo Shell fetches all the documents which matches any of the documents which the individual objects inside the array points to.
Observe the documents – it has some names which are in alphabetical order. Last document has an extra field called age. And another odd entry is a document with name as 25.
If $exists is true, it retrieves documents which has the specified field. If $exists is false, then it retrieves all the documents which do not have the specified field.
$regex: “e” retrieves all the documents in which small letter “e” is present. $regex: “^E” retrieves all the documents which has it’s name beginning letter as “E”. $regex: “h$” retrieves all the documents which has it’s name ending letter as “h”. $regex: “^[A-Z]” retrieves all the documents which has it’s name starting with characters “A” to “Z”. $regex: “^[A-E]” retrieves all the documents which has it’s name starting with characters “A” to “E”.
Note: There is more to regular expression, this video is just an introduction. We’ll cover more about regular expressions in a separate video of it’s own.
Today we shall see how we can compare strings using comparison operators like, $ne – not equal to $gt – greater than $gte – greater than or equal to $lt – less than $lte – less than or equal to
(In our video we have clearly illustrated the use of $lt and $gt. Your task is to understand it and try other comparison operators, and you can share your results in the comment section below.)
But in both cases the entry with name as 25 doesn’t appear. This concludes that, in MongoDB while we compare string/character using comparison operator, the comparison occurs only between strings and character and not with other datatypes.
Note: Lexicographical order: In mathematics, the lexicographic or lexicographical order is a generalization of the way the alphabetical order of words is based on the alphabetical order of their component letters.
<h1>#{user.name}</h1>
ul
li Age: #{user.age}
li Email: #{user._id}
ul
li
a(href="/user/#{user._id}/delete") Delete
<h1>#{user.name}</h1>
ul li Age: #{user.age} li Email: #{user._id}
ul li a(href="/user/#{user._id}/delete") Delete
This adds Delete link below each individual user information.
Delete Routes: remove() app.js
1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
app.get('/user/:id/delete', function(req, res){
user.remove({_id: req.params.id},
function(err){
if(err) res.json(err);
else res.redirect('/view');
});
});
var user = mongoose.model('emp', Schema);
app.get('/user/:id/delete', function(req, res){
user.remove({_id: req.params.id}, function(err){
if(err) res.json(err);
else res.redirect('/view');
});
});
Here we simply make use of app.get and the route we are defining is /user/:id/delete Once the user clicks on the delete link with the user id in it, the route gets triggered and by using remove() method upon user object, we fetch the user data with the particular id that the user passed in from the URL and delete it from our mongoDB collection.
Delete Routes: findByIdAndRemove() app.js
1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
app.get('/user/:id/delete', function(req, res){
user.findByIdAndRemove({_id: req.params.id},
function(err, docs){
if(err) res.json(err);
else res.redirect('/view');
});
});
var user = mongoose.model('emp', Schema);
app.get('/user/:id/delete', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, function(err, docs){
if(err) res.json(err);
else res.redirect('/view');
});
});
Here we are using findByIdAndRemove() method of mongoose module to find the requested user and delete the user document. Syntax is same as remove() method, only change is, findByIdAndRemove() method also returns result object to the callback method along with error object.
app.delete view/show.jade
1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
li Age: #{user.age}
li Email: #{user._id}
ul
li
a(href="/user/#{user._id}/edit") Edit
li
form(action="/user/#{user._id}", method="POST")
input(type="hidden", name="_method", value="DELETE")
button(type="submit") Delete
<h1>#{user.name}</h1>
ul li Age: #{user.age} li Email: #{user._id}
ul li a(href="/user/#{user._id}/edit") Edit li form(action="/user/#{user._id}", method="POST") input(type="hidden", name="_method", value="DELETE") button(type="submit") Delete
Here we replace the delete link with a delete button. Here the action field value is /user/#{user._id} and the method used is POST. But we are also passing a hidden input field which overrides the method from POST to DELETE inside our node application.
Delete Routes: app.delete() and findByIdAndRemove() app.js
1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id},
function(err, docs){
if(err) res.json(err);
else res.redirect('/view');
});
});
var user = mongoose.model('emp', Schema);
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, function(err, docs){
if(err) res.json(err);
else res.redirect('/view');
});
});
The findByIdAndRemove() method works the same way as explained above.
Delete Routes: app.delete() and remove() app.js
1
2
3
4
5
6
7
8
9
var user = mongoose.model('emp', Schema);
app.delete('/user/:id', function(req, res){
user.remove({_id: req.params.id},
function(err){
if(err) res.json(err);
else res.redirect('/view');
});
});
var user = mongoose.model('emp', Schema);
app.delete('/user/:id', function(req, res){
user.remove({_id: req.params.id}, function(err){
if(err) res.json(err);
else res.redirect('/view');
});
});
The remove() method works the same way as explained above.
ul
each user in users
li
a(href='/user/#{user._id}') #{user.name}
ul
each user in users li a(href='/user/#{user._id}') #{user.name}
Edit form view/edit-form.jade
1
2
3
4
5
6
7
8
9
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}")
input(type="hidden", name="_method", value="PUT")
p Name:
input(type="text", name="name", value="#{user.name}")
p Age:
input(type="number", name="age", value="#{user.age}")
p
input(type="submit")
<h1>Editing #{user.name}'s profile!</h1>
form(method="POST", action="/user/#{user._id}") input(type="hidden", name="_method", value="PUT") p Name: input(type="text", name="name", value="#{user.name}") p Age: input(type="number", name="age", value="#{user.age}") p input(type="submit")
Show Individual User Information view/show.jade
1
2
3
4
5
6
7
8
9
10
11
12
<h1>#{user.name}</h1>
ul
li Age: #{user.age}
li Email: #{user._id}
ul
li
a(href="/user/#{user._id}/edit") Edit
li
form(action="/user/#{user._id}", method="POST")
input(type="hidden", name="_method", value="DELETE")
button(type="submit") Delete
<h1>#{user.name}</h1>
ul li Age: #{user.age} li Email: #{user._id}
ul li a(href="/user/#{user._id}/edit") Edit li form(action="/user/#{user._id}", method="POST") input(type="hidden", name="_method", value="DELETE") button(type="submit") Delete
Main Node.js Application File, with Create, Read, Update and Delete Routes app.js
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id},
function(err, docs){
if(err) res.json(err);
else res.redirect('/view');
});
});
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id},
{
name: req.body.name,
age : req.body.age
}, function(err, docs){
if(err) res.json(err);
else
{
console.log(docs);
res.redirect('/user/'+req.params.id);
}
});
});
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else res.render('index', {users: docs})
});
});
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var express = require('express');
var http = require('http');
var path = require('path');
var mongoose = require('mongoose');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
mongoose.connect('mongodb://localhost/Company');
var Schema = new mongoose.Schema({
_id : String,
name: String,
age : Number
});
var user = mongoose.model('emp', Schema);
app.delete('/user/:id', function(req, res){
user.findByIdAndRemove({_id: req.params.id}, function(err, docs){
if(err) res.json(err);
else res.redirect('/view');
});
});
app.get('/user/:id/edit', function(req, res){
res.render('edit-form', {user: req.userId});
});
app.put('/user/:id', function(req, res){
user.findByIdAndUpdate({_id: req.params.id}, { name: req.body.name, age : req.body.age }, function(err, docs){ if(err) res.json(err);
else
{ console.log(docs); res.redirect('/user/'+req.params.id); } });
});
app.param('id', function(req, res, next, id){
user.findById(id, function(err, docs){
if(err) res.json(err);
else
{
req.userId = docs;
next();
}
});
});
app.get('/user/:id', function(req, res){
res.render('show', {user: req.userId});
});
app.get('/view', function(req, res){
user.find({}, function(err, docs){
if(err) res.json(err);
else res.render('index', {users: docs})
});
});
app.post('/new', function(req, res){
new user({
_id : req.body.email,
name: req.body.name,
age : req.body.age
}).save(function(err, doc){
if(err) res.json(err);
else res.redirect('/view');
});
});
var server = http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port'));
});
Routes / for new entries /view for viewing all the users /user/:id to see individual user information /user/:id/edit to edit individual user information
With these tutorials you can start building fully functional web application. But to make it more secure, incorporate sessions, validation and error handling.