-
mongo的安装
- 点击下载https://www.mongodb.com/download-center/community
- 点击exe程序一步一步向下安装直到结束
- 配置path环境,找到C:\Program Files\MongoDB\Server\3.4\bin这个目录。电脑属性==》高级==》环境变量==》编辑path==》添加刚刚这个目录到path
- 打开cmd,输入mongo,出现以下这些就说明配置成功了
-
数据库的连接与使用
- 新建mongo文件夹,复制目录
- 开启服务,打开cmd,输入mongod --dbpath F:\2019\node\mongo(你的路径名字)
- 管理数据库(ps:另开一个cmd,刚刚那个也不要关),输入mongo
-
数据库的增删改查
- 查看所有数据库show dbs
> show dbs admin 0.000GB local 0.000GB
- 清屏cls
- 使用并创建数据库 use <数据库名字>(ps:use就代表了已经创建这个数据库了)
> use school switched to db school
-
插入数据 db.<集合名字>.insert({"name":"希望小学1"}) (ps:集合名字自己命名,插入数据之后就会自动创建集合)
> db.class.insert({"name":"3年级"},{"name":"4年级"}) WriteResult({ "nInserted" : 1 })
-
显示集合名字 show collections
> show collections class student
-
查找所有数据 db.<集合名字>.find()
> db.student.find() { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" } { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" }
-
按条件查询,举个例子,查询年龄等于12的学生
> db.student.find({age:"12"}) { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
举个例子,查询年龄大于22的学生
> db.student.find({age:{$gt:"22"}}) { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" } { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" } { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" } { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" }
举个例子,查询年龄小于22的学生
> db.student.find({age:{$lt:"22"}}) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
举个例子,查询年龄小于等于12的学生
> db.student.find({age:{$lte:"12"}}) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
举个例子,查询年龄大于12小于52的学生
> db.student.find({age:{$lt:"52",$gt:"12"}}) { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" } { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" } { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }
举个例子,查询名字中有wangwu的学生
> db.student.find({name:/wangwu/}) { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" } { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" } { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }
举个例子,查询名字中以小开头的学生
> db.student.find({name:/^小/}) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
举个例子,查询指定列 name的数据
> db.student.find({},{name:1}) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红" } { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu" } { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu" } { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566" } { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby" } { "_id" : ObjectId("5c89df6f1eae9c63db0e3791"), "name" : "小刚" }
举个例子,查询按照年龄排序,升序1,降序-1
> db.student.find().sort({age:1}) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" } { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" } { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" } { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" } { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" }
举个例子,查询前3条数据
> db.student.find().limit(3) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" } { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
举个例子,查询后3条以后的数据
> db.student.find().skip(3) { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" } { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" } { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" } { "_id" : ObjectId("5c89df6f1eae9c63db0e3791"), "性别" : "男", "name" : "小刚" }
举个例子,查询2-5之间的数据
> db.student.find().limit(3).skip(2) { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" } { "_id" : ObjectId("5c89db3d1eae9c63db0e378e"), "name" : "wangwu", "age" : "32" } { "_id" : ObjectId("5c89db461eae9c63db0e378f"), "name" : "wangwu566", "age" : "32" }
举个例子,查询年龄为1或者年龄为12的数据
> db.student.find({$or:[{age:"1"},{age:"12"}]}) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
举个例子,查找第一条数据
> db.student.findOne() { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "name" : "小红", "age" : "1" }
举个例子,查询某个结果的条数
> db.student.find().count() 7
-
修改数据,举个例子,修改名字叫小红的,改成15岁
> db.student.update({"name":"小红"},{$set:{"age":"15"}}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
如果想要完整替换,就不要出现关键字$set
> db.student.update({"name":"小红"},{"age":"15"}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) > db.student.find() }) { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "age" : "15" } { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" }
-
删除数据db.collectionsNames.remove( {} )
> db.student.remove({"age":"32"}) WriteResult({ "nRemoved" : 2 }) > db.student.find() { "_id" : ObjectId("5c89d9791eae9c63db0e378b"), "age" : "15" } { "_id" : ObjectId("5c89d9941eae9c63db0e378c"), "name" : "丽丽", "age" : "51" } { "_id" : ObjectId("5c89db361eae9c63db0e378d"), "name" : "wangwu", "age" : "12" } { "_id" : ObjectId("5c89db591eae9c63db0e3790"), "name" : "baby", "age" : "52" } { "_id" : ObjectId("5c89df6f1eae9c63db0e3791"), "性别" : "男", "name" : "小刚" }
删除表db.collectionsNames.drop()
> show collections class student > db.class.drop() true > db.class.drop() false > show collections student >
删除数据库db.dropDatabase();
-
MongoDB 索引
索引是对数据库表中一列或多列的值进行排序的一种结构,可以让我们查询数据库变得更快。数字 1 表示 username 键的索引按升序存储,-1 表示 age 键的索引按照降序方式存储
- 创建索引:
> db.student.ensureIndex({"name":1}) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 2, "numIndexesAfter" : 2, "note" : "all indexes already exist", "ok" : 1 }
- 获取当前集合的索引
> db.student.getIndexes() [ { "v" : 2, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "school.student" }, { "v" : 2, "key" : { "name" : 1 }, "name" : "name_1", "ns" : "school.student" }, { "v" : 2, "key" : { "age" : 1 }, "name" : "age_1", "ns" : "school.student" } ]
- 删除索引
> db.user.dropIndex({"name":1}) { "ok" : 0, "errmsg" : "ns not found", "code" : 26, "codeName" : "NamespaceNotFound" }
-
使用import和export导入导出数据
- 使用import导入数据,注意,操作这个命令行要开启一个新的cmd或者退出当前mongo环境,否则报错,报错信息:[js] SyntaxError: missing ; before statement @(shell):1:15
mongoimport -d <数据库名字> -c <集合名字> --file <当前数据的路径>
ps:当前数据的路径可以直接将文件拖进来就可以生成。
- 使用export导出数据
mongoexport -d <数据库名> -c <集合名> -o <导出的路径>
json格式示例:
{ "title": "平台", "children": [{ "link": "https://github.com/DFairy", "title": "github", "description": "github平台" } ] } { "title": "JAVASCRIPT", "children": [{ "link": "https://www.sitepoint.com/", "title": "javascript-no-jquery", "description": "js写法" } ] }
-
使用nodejs操作数据库
文档地址参考:http://mongodb.github.io/node-mongodb-native/3.1/quick-start/quick-start/
- npm install mangodb --save-dev
- nodejs连接数据库
const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const express = require("express"); const app = express() const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'school'; // Create a new MongoClient const client = new MongoClient(url, { useNewUrlParser: true }); app.get('/', function(req, res) { // Use connect method to connect to the Server client.connect(function(err) { res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" }); if (err) { res.send("数据库连接失败"); return; } assert.equal(null, err); res.write("恭喜,数据库已经成功连接 \n"); console.log("Connected successfully to server"); const db = client.db(dbName); }); }) app.listen(8020)
控制台输入node app.js,刷新页面http://localhost:8020/出现数据库连接成功就代表连上数据库了
- 插入数据
const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const express = require("express"); const app = express() const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'school'; // Create a new MongoClient const client = new MongoClient(url, { useNewUrlParser: true }); app.get('/', function(req, res) { // Use connect method to connect to the Server client.connect(function(err) { res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" }); if (err) { res.send("数据库连接失败"); return; } assert.equal(null, err); res.write("恭喜,数据库已经成功连接 \n"); console.log("Connected successfully to server"); const db = client.db(dbName); insertDocuments(db, function() { client.close(); }) }); }) app.listen(8020) //插入数据 const insertDocuments = function(db, callback) { // Get the documents collection const collection = db.collection('student'); // Insert some documents collection.insertMany([ { name: "静静" }, { name: "忽略了" }, { name: "baby" } ], function(err, result) { assert.equal(err, null); assert.equal(3, result.result.n); assert.equal(3, result.ops.length); console.log("Inserted 3 documents into the collection"); callback(result); }); }
- 显示数据
const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const express = require("express"); const app = express() const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'school'; // Create a new MongoClient const client = new MongoClient(url, { useNewUrlParser: true }); app.get('/', function(req, res) { // Use connect method to connect to the Server client.connect(function(err) { res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" }); if (err) { res.send("数据库连接失败"); return; } assert.equal(null, err); res.write("恭喜,数据库已经成功连接 \n"); console.log("Connected successfully to server"); const db = client.db(dbName); findDocuments(db, function() { client.close(); }) }); }) app.listen(8020) const findDocuments = function(db, callback) { // Get the documents collection const collection = db.collection('student'); // Find some documents collection.find().toArray(function(err, docs) { assert.equal(err, null); console.log("Found the following records"); console.log(docs) callback(docs); }); }
-
改变数据
const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const express = require("express"); const app = express() const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'school'; // Create a new MongoClient const client = new MongoClient(url, { useNewUrlParser: true }); app.get('/', function(req, res) { // Use connect method to connect to the Server client.connect(function(err) { res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" }); if (err) { res.send("数据库连接失败"); return; } assert.equal(null, err); res.write("恭喜,数据库已经成功连接 \n"); console.log("Connected successfully to server"); const db = client.db(dbName); updateDocument(db, function() { client.close(); }) }); }) app.listen(8020) const updateDocument = function(db, callback) { // Get the documents collection const collection = db.collection('student'); // Update document where a is 2, set b equal to 1 collection.updateOne({ a: 2 }, { $set: { b: 1 } }, function(err, result) { assert.equal(err, null); assert.equal(1, result.result.n); console.log("Updated the document with the field a equal to 2"); callback(result); }); }
-
删除数据
const MongoClient = require('mongodb').MongoClient; const assert = require('assert'); const express = require("express"); const app = express() const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'school'; // Create a new MongoClient const client = new MongoClient(url, { useNewUrlParser: true }); app.get('/', function(req, res) { // Use connect method to connect to the Server client.connect(function(err) { res.writeHead(200, { "Content-Type": "text/html;charset=UTF8" }); if (err) { res.send("数据库连接失败"); return; } assert.equal(null, err); res.write("恭喜,数据库已经成功连接 \n"); console.log("Connected successfully to server"); const db = client.db(dbName); removeDocument(db, function() { client.close(); }) }); }) app.listen(8020) const removeDocument = function(db, callback) { // Get the documents collection const collection = db.collection('student'); // Delete document where a is 3 collection.deleteOne({ a: 3 }, function(err, result) { assert.equal(err, null); assert.equal(1, result.result.n); console.log("Removed the document with the field a equal to 3"); callback(result); }); }
-
使用mongoose连接数据库
举个下面的例子,具体的看官方文档,介绍的很详细:https://cn.mongoosedoc.top/docs/index.html
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true })
var db = mongoose.connection
db.on('error', () => {
console.log("连接失败")
})
db.on('open', () => {
console.log('连接成功')
})
var kittySchema = mongoose.Schema({
name: String
})
kittySchema.methods.speak = function() {
var greeting = this.name ? "my name is " + this.name : "I dont have name"
}
var kitty = mongoose.model('kitty', kittySchema)
var miao = new kitty({ name: 'mimi' })
miao.speak()
// miao.save((err, miao) => {
// if (err) {
// console.log(err)
// }
// miao.speak()
// })
kitty.find((err, kittens) => {
if (err) {
console.log(err)
}
console.log(kittens)
})