码迷,mamicode.com
首页 > 数据库 > 详细

MongoDB基操

时间:2019-01-19 11:20:22      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:指定   更新   跳过   显示   基础上   agg   基本概念   防止   语法   

基本概念

  • database 数据库 包含多个collection
    • collection 集合 包含多个文档document(类JSON对象)
      • document 文档 一个文档对象中包含多个key-value键值对

入门

基本命令

  1. show dbs列出全部数据库
  2. db 查看当前数据库
  3. use db_name 切换到/创建数据库db_name
  4. show collections 列出当前库中的所有collection
  5. db.createCollectioin(c_name,{参数文档}) 创建一个名为c_name的collection,至于参数文档以后再说
  6. db.c_name.insert({文档对象}) 往c_name集合中插入数据
  7. db.c_name.find() 查询c_name中的所有document数据
  8. db.c_name.drop() 删除集合
  9. db.dropDatabase()删除数据库

增删改查

语法

db.集合名称.insert(document)
插入文档时,如果不指定_id参数,MongoDB会为文档分配一个唯一的ObjectId

插入方式1
db.stu.insert({name:‘gj‘,gender:1})

插入方式2
s1={_id:‘20160101‘,name:‘hr‘}
s1.gender=0
db.stu.insert(s1)

操作

> db.createCollection(‘test‘)
{ "ok" : 1 }
> db.test.insert({book:‘红楼梦‘,author:‘曹雪芹‘,roles:[‘贾宝玉‘,‘林黛玉‘,‘薛宝钗‘]})
WriteResult({ "nInserted" : 1 })
> db.test.insert({name:‘张三‘})
WriteResult({ "nInserted" : 1 })
> db.test.insert({key:‘value‘,k1:{k2:‘value2‘,k3:‘value3‘}})
WriteResult({ "nInserted" : 1 })

语法

db.集合名称.remove(
   <query>,
   {
     justOne: <boolean>
   }
)

只删除匹配到的第一条
db.stu.remove({gender:0},{justOne:true})
全部删除
db.stu.remove({})
  • 参数query:可选,删除的文档的条件
  • 参数justOne:可选,如果设为true或1,则只删除一条,默认false,表示删除多条

操作

> db.test.remove({‘name‘:‘张三‘},{justOne:false})
WriteResult({ "nRemoved" : 1 })
> db.test.find()
{ "_id" : ObjectId("5c419e5afbd19a2f55a0ddd9"), "book" : "红楼梦", "author" : "曹雪芹", "roles" : [ "贾宝玉", "林黛玉", "薛宝钗" ] }
{ "_id" : ObjectId("5c419eebfbd19a2f55a0dddb"), "key" : "value", "k1" : { "k2" : "value2", "k3" : "value3" } }
> 

语法

db.集合名称.update(
   <query>,
   <update>,
   {multi: <boolean>}
)

全文档更新
db.stu.update({name:‘hr‘},{name:‘mnc‘})

指定属性更新,通过操作符$set
db.stu.insert({name:‘hr‘,gender:0})
db.stu.update({name:‘hr‘},{$set:{name:‘hys‘}})

修改多条匹配到的数据
db.stu.update({},{$set:{gender:0}},{multi:true})
  • 参数query:查询条件,类似sql语句update中where部分
  • 参数update:更新操作符,类似sql语句update中set部分
  • 参数multi:可选,默认是false,表示只更新找到的第一条记录,值为true表示把满足条件的文档全部更新

操作

> db.test.update({key:‘value‘},{$set:{key:‘什么鬼‘}},{multi:true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test.find()
{ "_id" : ObjectId("5c419e5afbd19a2f55a0ddd9"), "book" : "红楼梦", "author" : "曹雪芹", "roles" : [ "贾宝玉", "林黛玉", "薛宝钗" ] }
{ "_id" : ObjectId("5c419eebfbd19a2f55a0dddb"), "key" : "什么鬼", "k1" : { "k2" : "value2", "k3" : "value3" } }
> 

语法

db.集合名称.find()  简单列出全部数据
db.集合名称.find().pretty() 好看的列出全部数据
db.集合名称.findOne() 查一条数据
db.集合名称.find({查询参数文档}) 指定参数的查询

操作

> db.test.find({book:‘红楼梦‘})
{ "_id" : ObjectId("5c419e5afbd19a2f55a0ddd9"), "book" : "红楼梦", "author" : "曹雪芹", "roles" : [ "贾宝玉", "林黛玉", "薛宝钗" ] }
> db.test.find({book:‘红楼梦‘}).pretty()
{
    "_id" : ObjectId("5c419e5afbd19a2f55a0ddd9"),
    "book" : "红楼梦",
    "author" : "曹雪芹",
    "roles" : [
        "贾宝玉",
        "林黛玉",
        "薛宝钗"
    ]
}
> db.test.findOne({book:‘红楼梦‘})
{
    "_id" : ObjectId("5c419e5afbd19a2f55a0ddd9"),
    "book" : "红楼梦",
    "author" : "曹雪芹",
    "roles" : [
        "贾宝玉",
        "林黛玉",
        "薛宝钗"
    ]
}

深入查询

比较运算符

  1. 等于
  2. $lt小于
  3. $lte 小于等于
  4. $gt 大于
  5. $gte 大于等于
  6. $ne not equal
年龄=15
> db.student.find({age:15})
{ "_id" : ObjectId("5c41d2ce2ac421ae45483f61"), "name" : "micheal", "gender" : 1, "age" : 15 }

年龄>15
> db.student.find({age:{$gt:15}})
{ "_id" : ObjectId("5c41d2f62ac421ae45483f63"), "name" : "alex", "gender" : 1, "age" : 41 }
{ "_id" : ObjectId("5c41d30a2ac421ae45483f64"), "name" : "amada", "gender" : 0, "age" : 29 }
{ "_id" : ObjectId("5c41d3252ac421ae45483f65"), "name" : "talor", "gender" : 0, "age" : 27 }
{ "_id" : ObjectId("5c41d3342ac421ae45483f66"), "name" : "bill", "gender" : 0, "age" : 62 }
{ "_id" : ObjectId("5c41d3422ac421ae45483f67"), "name" : "jobs", "gender" : 0, "age" : 46 }

年龄>=15
> db.student.find({age:{$gte:15}})
{ "_id" : ObjectId("5c41d2ce2ac421ae45483f61"), "name" : "micheal", "gender" : 1, "age" : 15 }
{ "_id" : ObjectId("5c41d2f62ac421ae45483f63"), "name" : "alex", "gender" : 1, "age" : 41 }
{ "_id" : ObjectId("5c41d30a2ac421ae45483f64"), "name" : "amada", "gender" : 0, "age" : 29 }
{ "_id" : ObjectId("5c41d3252ac421ae45483f65"), "name" : "talor", "gender" : 0, "age" : 27 }
{ "_id" : ObjectId("5c41d3342ac421ae45483f66"), "name" : "bill", "gender" : 0, "age" : 62 }
{ "_id" : ObjectId("5c41d3422ac421ae45483f67"), "name" : "jobs", "gender" : 0, "age" : 46 }

逻辑运算符

  1. and 默认
  2. or 使用$or
年龄大于15 and 小于30
> db.student.find({age:{$gt:15},age:{$lt:30}})
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }
{ "_id" : ObjectId("5c41d2c02ac421ae45483f60"), "name" : "rose", "gender" : 0, "age" : 12 }
{ "_id" : ObjectId("5c41d2ce2ac421ae45483f61"), "name" : "micheal", "gender" : 1, "age" : 15 }
{ "_id" : ObjectId("5c41d2e42ac421ae45483f62"), "name" : "peppa", "gender" : 0, "age" : 4 }
{ "_id" : ObjectId("5c41d30a2ac421ae45483f64"), "name" : "amada", "gender" : 0, "age" : 29 }
{ "_id" : ObjectId("5c41d3252ac421ae45483f65"), "name" : "talor", "gender" : 0, "age" : 27 }

年龄小于15 and gender=1
> db.student.find({age:{$lt:15},gender:1})
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }

name=‘jack‘ or name=‘rose‘
> db.student.find({$or:[{name:‘jack‘},{name:‘rose‘}]})
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }
{ "_id" : ObjectId("5c41d2c02ac421ae45483f60"), "name" : "rose", "gender" : 0, "age" : 12 }

(age=12 or age=13) and gender=1
> db.student.find({$or:[{age:13},{age:12}],gender:1})
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }

范围运算符

  1. $in在某个范围
  2. $nin 不在某个范围
> db.student.find({age:{$in:[15,20]}})
{ "_id" : ObjectId("5c41d2ce2ac421ae45483f61"), "name" : "micheal", "gender" : 1, "age" : 15 }
相当于age=15 or age=20

正则表达式查询

使用// $regex

name 以j开头的
> db.student.find({name:/^j/})
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }
{ "_id" : ObjectId("5c41d3422ac421ae45483f67"), "name" : "jobs", "gender" : 0, "age" : 46 }

name 以m开头的
> db.student.find({name:{$regex:‘^m‘}})
{ "_id" : ObjectId("5c41d2ce2ac421ae45483f61"), "name" : "micheal", "gender" : 1, "age" : 15 }

自定义查询

使用$where后面写一个函数,返回满足条件的数据

age<15
> db.student.find({$where:function(){return this.age<15}})
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }
{ "_id" : ObjectId("5c41d2c02ac421ae45483f60"), "name" : "rose", "gender" : 0, "age" : 12 }
{ "_id" : ObjectId("5c41d2e42ac421ae45483f62"), "name" : "peppa", "gender" : 0, "age" : 4 }

MongoDB函数

skip(number)

在查询结果集的基础上跳过number条数据

limit(number)

在查询结果集的基础上截取number条数据

db.stu.find().skip(5).limit(4)
两个连起来正好相当于mysql中的 limit 5,4

sort()

对结果集进行排序

语法 sort({name:1,age:-1,....})
1 升序号
-1 降序
按姓名升序排列 按年龄降序排列
> db.student.find().sort({name:1,age:-1})
{ "_id" : ObjectId("5c41d2f62ac421ae45483f63"), "name" : "alex", "gender" : 1, "age" : 41 }
{ "_id" : ObjectId("5c41d30a2ac421ae45483f64"), "name" : "amada", "gender" : 0, "age" : 29 }
{ "_id" : ObjectId("5c41d3342ac421ae45483f66"), "name" : "bill", "gender" : 0, "age" : 62 }

按年龄升序排列
> db.student.find().sort({age:1})
{ "_id" : ObjectId("5c41d2e42ac421ae45483f62"), "name" : "peppa", "gender" : 0, "age" : 4 }
{ "_id" : ObjectId("5c41d2c02ac421ae45483f60"), "name" : "rose", "gender" : 0, "age" : 12 }
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }

count()

统计结果集中的文档条数

  1. db.c_name.find().count()
  2. db.c_name.count({条件文档对象})
统计gender=1的人数
> db.student.find({gender:1}).count()
3

> db.student.count({gender:1})
3

distinct()

对数据进行去重

db.集合名称.distinct(‘去重字段‘,{条件})

> db.student.distinct(‘gender‘,{age:{$gt:10}})
[ 1, 0 ]

进阶

投影

db.集合名称.find({},{字段名称:1,...})

设置为1代表显示

不设置或设为0代表不显示

_id必须设置为0才不显示

> db.student.find({},{_id:0,name:1})
{ "name" : "jack" }
{ "name" : "rose" }
{ "name" : "micheal" }
{ "name" : "peppa" }
{ "name" : "alex" }
{ "name" : "amada" }
{ "name" : "talor" }
{ "name" : "bill" }
{ "name" : "jobs" }

聚合

db.集合名称.aggregate([{管道:{表达式}}])

aggregate用于计算数据,类sql中的sum()、avg()这些聚合函数的功能

管道

管道 作用
$group 将文档分组,可用于统计结果
$match 过滤数据,只输出符合条件的文档
$project 修改输入文档的结构,重命名 增删filed 创建计算结果
$sort 排序
$limit $skip 类似 mysql limit 2,5
$unwind 将数组型字段进行拆分

表达式

表达式:‘$列名‘

处理输入文档并输出

表达式 作用
$sum 计算总和,$sum:1 同count表示计数
$avg 求平均
$min $max 最大、最小值
$push 在结果文档中插入值到一个数组中
$first $last 根据资源文档的排序获取首、尾文档数据
$push的用法
> db.student.aggregate([
    {$group:
        {_id:‘$gender‘,name:{$push:‘$name‘}}
    }
])
{ "_id" : 0, "name" : [ "rose", "peppa", "amada", "talor", "bill", "jobs" ] }
{ "_id" : 1, "name" : [ "jack", "micheal", "alex" ] }
> 
如果使用$push:‘$$ROOT‘会将整个文档对象添加到name数组中
$group
$group 按gender分组  统计男女同学数  group by _id
> db.student.aggregate([
    {$group:
        {_id:‘$gender‘,total:{$sum:1} }
    }
])
{ "_id" : 0, "total" : 6 }
{ "_id" : 1, "total" : 3 }

group by null表示将所有数据分为一组
> db.student.aggregate([
    {$group:
        {_id:null,total:{$sum:1},avgAge:{$avg:‘$age‘}}
    }
])
{ "_id" : null, "total" : 9, "avgAge" : 27.666666666666668 }
$match
查询年龄大于20的学生
> db.student.find({age:{$gt:20}})
> db.student.aggregate([{$match:{age:{$gt:20}}}])

查询年龄大于20的男生、女生人数
> db.student.aggregate([
    {$match:{age:{$gt:20}}},
    {$group:{_id:‘$gender‘,total:{$sum:1}}}
])
{ "_id" : 0, "total" : 4 }
{ "_id" : 1, "total" : 1 }
$project
> db.student.aggregate([{$project:{_id:0,name:1,age:1}}])

> db.student.find({},{_id:0,name:1,age:1})
就是find查询的投影

查询男生、女生人数,输出人数
> db.student.aggregate([{$group:{_id:‘$gender‘,total:{$sum:1}}},{$project:{_id:0,total:1}}])
{ "total" : 6 }
{ "total" : 3 }
$sort
按age降序排列
> db.student.aggregate([{$sort:{age:-1}}])
{ "total" : 6 }
{ "total" : 3 }

查询男生、女生人数,按人数降序
> db.student.aggregate([{$group:{_id:‘$gender‘,total:{$sum:1}}},{$sort:{total:-1}}])
{ "_id" : 0, "total" : 6 }
{ "_id" : 1, "total" : 3 }
$skip $limit

作用就像mysql中的limit x,y , 两者是有先后顺序的,skip要用在在limit前面。

按age升序排列  limit 0,3
> db.student.aggregate([
    {$sort:{age:1}},
    {$skip:0},
    {$limit:3}
])
{ "_id" : ObjectId("5c41d2e42ac421ae45483f62"), "name" : "peppa", "gender" : 0, "age" : 4 }
{ "_id" : ObjectId("5c41d2c02ac421ae45483f60"), "name" : "rose", "gender" : 0, "age" : 12 }
{ "_id" : ObjectId("5c41d2b22ac421ae45483f5f"), "name" : "jack", "gender" : 1, "age" : 13 }
$unwind

展开、分开 对某个字段值(值的类型为数组)进行拆分

  • 语法1 db.集合名称.aggregate([{$unwind:‘$字段名称‘}])

  • 语法2

    处理空数组、非数组、无字段、null情况
    db.集合名称.aggregate([{
        $unwind:{
            path:‘$字段名称‘,
            preserveNullAndEmptyArrays:<boolean>#防止数据丢失
        }
    }])
> db.student.insert({name:‘mark‘,gender:1,hobby:[‘smoking‘,‘drinking‘,‘perm‘]})
WriteResult({ "nInserted" : 1 })

> db.student.aggregate([{$unwind:‘$hobby‘},{$project:{_id:0}}])
{ "name" : "mark", "gender" : 1, "hobby" : "smoking" }
{ "name" : "mark", "gender" : 1, "hobby" : "drinking" }
{ "name" : "mark", "gender" : 1, "hobby" : "perm" }
{ "name" : "java", "gender" : 0, "hobby" : "coding" }

> db.student.aggregate([{$unwind:{path:‘$hobby‘,preserveNullAndEmptyArrays:true}},{$project:{_id:0}}])
{ "name" : "jack", "gender" : 1, "age" : 13 }
{ "name" : "rose", "gender" : 0, "age" : 12 }
{ "name" : "micheal", "gender" : 1, "age" : 15 }
{ "name" : "peppa", "gender" : 0, "age" : 4 }
{ "name" : "alex", "gender" : 1, "age" : 41 }
{ "name" : "amada", "gender" : 0, "age" : 29 }
{ "name" : "talor", "gender" : 0, "age" : 27 }
{ "name" : "bill", "gender" : 0, "age" : 62 }
{ "name" : "jobs", "gender" : 0, "age" : 46 }
{ "name" : "mark", "gender" : 1, "hobby" : "smoking" }
{ "name" : "mark", "gender" : 1, "hobby" : "drinking" }
{ "name" : "mark", "gender" : 1, "hobby" : "perm" }
{ "name" : "java", "gender" : 0, "hobby" : "coding" }
{ "name" : "ruby", "gender" : 1, "hobby" : null }

MongoDB基操

标签:指定   更新   跳过   显示   基础上   agg   基本概念   防止   语法   

原文地址:https://www.cnblogs.com/endurance9/p/10290523.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!