# mongodb **Repository Path**: zjcgit/mongodb ## Basic Information - **Project Name**: mongodb - **Description**: mongodb学习记录 - **Primary Language**: SQL - **License**: GPL-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-02-07 - **Last Updated**: 2021-02-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### Mongodb常用命令 ##### 1. 插入数据 db.集合名.insert(数据) ``` // 插入一条数据 db.Test.insert({username: "风珝", age: 16}) // 插入多条数据 db.user.insert([{username: "风珝", age: 19},{username: "刘俊", age:20 }]) // 插入多条数据不对称的情况下 db.user.insert([{username: "欧鸡", age: 19},{username: "罗鸡", age:20, sex: "女" }]) ``` ##### 2.查找数据 db.集合名.find(条件,要显示的字段名(省略则查找全部)) ###### 2.1 普通查找 ``` // 查找全部数据 db.user.find() // 查找age=19的 db.user.find({age: 19}) // 查找age=18的并指定只显示username(0:不显示,1:显示) db.user.find({age: 19},{username: 1}) // 查找age=20的并指定除了username都显示 db.user.find({age: 20},{username: 0}) // 查询所有年龄不等于19岁的 db.user.find({ age: { $ne: 19 } }) ``` ###### 2.2 复杂条件查询 ``` // 查询age<20岁的 db.user.find({ age: {$lt: 20} }) // 查询age<=20岁的 db.user.find({ age: {$lte: 20} }) // 同理大于则gt,大于等于则gte ============================== // 查找age在是18或者20的 db.user.find({ age: { $in: [18,20] } }) // 匹配所有符合条件的 db.user.find({ username: { $all: ['风珝'] } }) // 匹配所有age!=18和age!=20的 db.user.find({ age: { $nin: [18,20] } }) // 匹配所有age不大于19的: $not取反 db.user.find({ age: { $not:{ $gt: 19 } } }) // 使用正则表达式查询username带风的 /i:不区分大小写 /g全局匹配 db.user.find({ username: { $regex: /风/ig } }) // 查询age>18岁并且sex=男的 db.user.find({ age: { $gt: 18 }, sex: { $eq: '男' } }) // 查询age在18-19岁或者username带'风'的 , $or表示或传入数组类型的参数 db.user.find({ $or: [ { age: { $in: [18,19]} }, { username: {$regex: /风/ig} } ] }) ``` ###### 2.3.数据分页 ``` // 取出5条数据 db.user.find().limit(5) // 跳过5条数据取出5条数据 db.user.find().skip(5).limit(5) ``` ###### 2.4.数据排序 ``` // 将取出的数据按age正序排列 1:正序, -1: 逆序 db.user.find().skip(2).limit(10).sort({age: 1}) ``` ###### 2.5 多级数据查询 ``` // 查找goods数组下含cat_id=4的文档; $elemMatch表示数组元素 db.getCollection("goods_list").find({ goods: {$elemMatch: {cat_id: 4}} }) ``` ###### 2.6 查询数据个数 ``` db.getCollection("user").count({条件}) ``` ##### 3.更新数据 db.集合名.update(查找条件,更新条件) ``` // 将username=风珝的age改为20 db.user.update({username: "风珝"}, { $set: { age: 20 } }) // 将username=风珝的age增加2 db.user.update({username: "风珝"}, { $inc: { age: 2 } }) // 将username=风珝的age减少4 db.user.update({username: "风珝"}, { $inc: { age: -4 } }) // 将username带'风'的age删除 此时age可为任何值 db.user.update({ username: {$regex: /风/ig} }, { $unset: { age: 1 } }) // 将username带'风'的like数组中添加爱好 like必须是数组类型才可以使用$push db.user.update({ username: {$regex: /风/ig} }, { $push: { like: "编程" } }) // 将username带'风'的like中删除最后一个值 1:删除最后一个值 -1: 从头删除第一个值 db.user.update({ username: {$regex: /风/ig} }, { $pop: { like: 1 } }) // 将username带'风'的like中的指定值删除 db.user.update({ username: {$regex: /风/ig} }, { $pull : { like: "编程" } }) ``` ##### 4.删除数据 ``` //删除username="风和"的文档 db.user.remove({ username: "风和" }) // 只删除一个age=18的文档 db.user.remove({ age: 18 },{ justOne: true }) ``` ### NodeJs连接Mongodb ##### 1.下载依赖包 ``` npm install mongodb ``` ##### 2.创建连接执行操作 ###### 2.1 创建集合 ``` var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/Test"; MongoClient.connect(url, { useNewUrlParser: true,useUnifiedTopology: true }, function (err, db) { if (err) throw err; console.log('数据库已创建'); var dbase = db.db("Test"); // 创建集合 dbase.createCollection("site",(err,res)=>{ if(err) throw err console.log('集合创建成功!') }) }); ``` ###### 2.2 插入数据 ``` dbase.collection("site").insertOne({name: "风珝", age: 10}, (err,res)=>{ if(err) throw err console.log('数据插入成功!') }) ``` ###### 2.3插入多条数据 ``` // 插入多条数据 let obj = [ {name: "欧鸡", age: 20}, {name: "罗鸡",age: 18}, {name: "阿萨德", age: 22} ] dbase.collection("site").insertMany(obj,(err,res)=>{ if(err) throw err console.log('插入多条数据成功!') }) ``` ###### 2.4查询数据 ``` // 查询全部数据 dbase.collection('site').find({}).toArray((err,res)=>{ if(err) throw err console.log(res) }) ``` ```js // 根据查询条件查询 let condition = { name: {$regex: /鸡/ig}, age: {$gt: 18} } dbase.collection('site').find(condition).toArray((err,res)=>{ if(err) throw err console.log(res) }) // 查询like数组只有普通数据时如like: [1,2,3,4]总like含有1的 dbase.collection('site').find({like: 1}).toArray((err,res)=>{ if(err) throw err console.log(res) }) // 查询like数组只有普通数据时如like: [1,2,3,4]总like含有1和2的 dbase.collection('site').find({$and: [{like: 1},{like: 2}]}).toArray((err,res)=>{ if(err) throw err console.log(res) }) // 查询like数组只有对象数据时如like: [{age: 1},{age: 2}],总like中age=1的 dbase.collection('site').find({ like.age: 1 // 或者 like: {elemMatch: {age: 1}} //elemMatch匹配数组中每个元素 }).toArray((err,res)=>{ if(err) throw err console.log(res) }) // 查询个数 db.collection('user').countDocuments({},(err,res)=>{ console.log(res) }) ``` ``` //只返回指定字段: projerct() dbase.collection('goods_detail').find(condition).project({_id:0, goods_name:1}).limit(1).toArray((err,res)=>{ console.log(res) }) ``` ###### 2.5更新数据 ``` //更新一条数据 dbase.collection('site').updateOne({name: {$regex: /鸡/ig}}, {$set: {age: 21}}, (err,res)=>{ if(err) throw err console.log('更新成功') }) ``` ``` // 更新多条数据 dbase.collection('site').updateMany({name: {$regex: /鸡/ig}}, {$set: {age: 22}}, (err,res)=>{ if(err) throw err console.log('更新成功') }) ``` ###### 2.6删除数据 ``` // 删除数据 dbase.collection('site').deleteOne({name: '阿萨德'},(err,res)=>{ if(err) throw err console.log("删除成功") console.log(res) }) ``` ###### 2.7查询结果排序 ``` dbase.collection("site").find().sort({age: -1}).toArray(function(err, result) { if (err) throw err; console.log(result); db.close(); }); ``` ###### 2.8分页查询 ``` // 查询结果分页 dbase.collection('site').find().skip(1).limit(1).toArray((err,res)=>{ if (err) throw err console.log(res) }) ``` ###### 2.9 删除集合 ``` // 删除 test 集合 dbase.collection("site").drop(function(err, delOK) { // 执行成功 delOK 返回 true,否则返回 false if (err) throw err; if (delOK) console.log("集合已删除"); }); ``` ###### 拓展 Promise操作 ``` const MongoClient = require("mongodb").MongoClient; const url = "mongodb://localhost/"; MongoClient.connect(url, { useNewUrlParser: true }).then((conn) => { console.log("数据库已连接"); const test = conn.db("testdb").collection("test"); // 增加 test.insertOne({ "site": "runoob.com" }).then((res) => { // 查询 return test.find().toArray().then((arr) => { console.log(arr); }); }).then(() => { // 更改 return test.updateMany({ "site": "runoob.com" }, { $set: { "site": "example.com" } }); }).then((res) => { // 查询 return test.find().toArray().then((arr) => { console.log(arr); }); }).then(() => { // 删除 return test.deleteMany({ "site": "example.com" }); }).then((res) => { // 查询 return test.find().toArray().then((arr) => { console.log(arr); }); }).catch((err) => { console.log("数据操作失败" + err.message); }).finally(() => { conn.close(); }); }).catch((err) => { console.log("数据库连接失败"); }); ```