mongodb
非关系型数据库nosql.
没有行列的说法,只有collection 文档 相对老的数据的说法就是表和记录。
安装:
brew update
brew install mongodb
安装的路径:
cd /usr/local/Cellar/mongodb/3.4.3/bin
启动:brew services start mongodb
关闭:brew services stop mongodb
浏览器打开网址:localhost:27017
并在bin
的文件目录下运行命令./mongo
命令show dbs
可以查看已经创建的数据库
test 是我建的一个数据库
show dbs //显示数据库
db // 查看已选定的数据库
use test //使用某个数据库 没有则新建
db.createColletion(‘user’) //创建集合
user 是我创建的一个集合
db. user.insert({‘name’:’byc’}) //插入一条记录
db. user.find() //查找所有记录
db.user.findOne();
db.dropDatabase() //删除数据库
db. user.drop //删除指定集合
show collections //显示所有集合
db. user.save({}) //插入记录db.test.update({‘_id’,1},{$set:{name:’test’,age:20}})
db. user.remove({}) //删除所有集合
for(var i=1;i<=10;i++){db.test.insert({"name":"king"+i,"age":i})} //循环插入10条记录
db.user.find().pretty() //格式化显示查询结果
db.user.find().count() //查询数据条数
db.user.find({"age":5}) /查找age是5的条目
db.user.find({"age":{$gt:5}}) //查找age大于5的条目
db.user.find({"age":{$gt:5}}).sort({"age":1}) //查找age大于5的条目且升序排列
db.user.find({"age":{$gt:5}}).sort({"age":1}) //查找age大于5的条目且升序排列
db.user.find({"age":{$gt:5}}).sort({"age”:-1}) //查找age大于5的条目且降序排列
图形化管理工具:
Robomongo
nodejs连接数据库:
安装依赖pack: npm install mongoose
如果不安装则报错找不到mongodb
e.g:
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
var db = new mongodb.Db('test', server, {safe:true});
//连接db
db.open(function(err, db){
if(!err){
console.log('connect db');
// 连接Collection(可以认为是mysql的table)
// 第1种连接方式
// db.collection('mycoll',{safe:true}, function(err, collection){
// if(err){
// console.log(err);
// }
// });
// 第2种连接方式
db.createCollection('user', {safe:true}, function(err, collection){
if(err){
console.log(err);
}else{
//新增数据
// var tmp1 = {id:'1',title:'hello',number:1};
// collection.insert(tmp1,{safe:true},function(err, result){
// console.log(result);
// });
//更新数据
// collection.update({title:'hello'}, {$set:{number:3}}, {safe:true}, function(err, result){
// console.log(result);
// });
// 删除数据
// collection.remove({title:'hello'},{safe:true},function(err,result){
// console.log(result);
// });
// console.log(collection);
// 查询数据
var tmp1 = {title:'hello'};
var tmp2 = {title:'world'};
collection.insert([tmp1,tmp2],{safe:true},function(err,result){
console.log(result);
});
collection.find().toArray(function(err,docs){
console.log('find');
console.log(docs);
});
collection.findOne(function(err,doc){
console.log('findOne');
console.log(doc);
});
}
});
// console.log('delete ...');
// //删除Collection
// db.dropCollection('mycoll',{safe:true},function(err,result){
// if(err){
// console.log('err:');
// console.log(err);
// }else{
// console.log('ok:');
// console.log(result);
// }
// });
}else{
console.log(err);
}
});
mongodb 通过 mongoose来建模
1.Schema(模式定义)
e.g.:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MovieSchema = new Schema({
director: String,
title: String,
language: String,
country: String,
summary: String,
flash: String,
poster: String,
year: Number,
meta: {
createAt: {
type: Date,
default: Date.now()
},
updateAt: {
type: Date,
default: Date.now()
}
}
});
MovieSchema.pre('save', function(next) {
if (this.isNew) {
this.meta.createAt = this.meta.updateAt = Date.now();
}
else {
this.meta.updateAt = Date.now();
}
next();
});
MovieSchema.statics = {
fetch: function(cb) {
return this
.find({})
.sort('meta.updateAt')
.exec(cb);
},
findById: function(id, cb) {
return this
.findOne({_id: id})
.exec(cb);
}
};
module.exports = MovieSchema;
2.Model(编译模型)
e.g.:
var mongoose = require('mongoose');
var MovieSchema = require('../schemas/movie');
var Movie = mongoose.model('Movie', MovieSchema);
module.exports = Movie;
3.Documents (文档实例化)
var mongoose = require('mongoose');
var dbUrl = 'mongodb://localhost/imooc';
mongoose.connect(dbUrl);
路由index.js:
var express = require('express');
var router = express.Router();
var Movie = require('../models/movie');
/* GET home page. */
router.get('/', function (req, res, next) {
Movie.fetch(function (err, movies) {
if (err) {
console.log(err);
}
res.render('index', {
title: 'imooc首页',
movies: movies
});
});
});
router.get('/movie/:id', function (req, res, next) {
var id = req.params.id;
Movie.findById(id, function (err, movie) {
if (err) {
console.log(err);
}
res.render('detail', {
title: "imooc 详情页",
movie: movie
});
});
});
module.exports = router;
路由users.js:
var express = require('express');
var router = express.Router();
var Movie = require('../models/movie');
var _ = require('underscore');
/* POST new movie. */
router.post('/movie/new', function (req, res, next) {
var id = req.body.movie._id;
var movieObj = req.body.movie;
var _movie;
if (id !== "undefined") {
Movie.findById(id, function (err, movie) {
if (err) {
console.log(err);
}
_movie = _.extend(movie, movieObj);
_movie.save(function (err, movie) {
if (err) {
console.log(err);
}
res.redirect('/movie/' + movie._id);
});
});
} else {
_movie = new Movie({
director: movieObj.director,
title: movieObj.title,
country: movieObj.country,
language: movieObj.language,
year: movieObj.year,
poster: movieObj.poster,
flash: movieObj.flash,
summary: movieObj.summary,
});
_movie.save(function (err, movie) {
if (err) {
console.log(err);
}
res.redirect('/movie/' + movie._id);
});
}
});
router.get('/movie', function (req, res, next) {
res.render('admin', {
title: "imooc 后台录入页",
movie: {
title: '',
country: '',
year: '',
poster: '',
flash: '',
director: '',
summary: '',
language: ''
}
});
});
router.get('/list', function (req, res, next) {
Movie.fetch(function (err, movies) {
if (err) {
console.log(err);
}
res.render('list', {
title: 'imooc管理员列表',
movies: movies
});
});
});
router.get('/movie/update/:id', function (req, res, next) {
var id = req.params.id;
Movie.findById(id, function (err, movie) {
if (err) {
console.log(err);
}
res.render('admin', {
title: "imooc 后台更新页",
movie: movie
});
});
});
module.exports = router;
网友评论