MongDB篇,第三章:数据库知识3

MongDB    数据库知识3

 修改器

$inc  对某个域的值进行加减修改

$mul  对某个域的值进行乘法修改

$min  如果筛选的文档指定的值小于min则不修改,如果大于min 给定的值则修改为min值;

$max  如果筛选的文档指定域的值大于max值则不变,小于max值则修改为max值;

> use stu
switched to db stu
> stu.class1.insert(name:'xiaoming',age:21,sex:'m')
2018-07-21T18:01:16.080+0800 E QUERY    [js] SyntaxError: missing ) after argument list @(shell):1:22
> stu.class1.insert({name:'xiaoming',age:21,sex:'m'})
2018-07-21T18:01:30.062+0800 E QUERY    [js] ReferenceError: stu is not defined :
@(shell):1:1
> use stu
switched to db stu
> stu.class1.insert({name:'xiaoming',age:21,sex:'m'})
2018-07-21T18:01:45.167+0800 E QUERY    [js] ReferenceError: stu is not defined :
@(shell):1:1
> db.class1.insert({name:'xiaoming',age:21,sex:'m'})
WriteResult({ "nInserted" : 1 })
>
> db.class1.insert({name:'lili',age:19,sex:'w'})
WriteResult({ "nInserted" : 1 })
> db.class1.insert({name:'tom',age:22,sex:'m'})
WriteResult({ "nInserted" : 1 })
> db.class1.insert({name:'ailee',age:20,sex:'w'})
WriteResult({ "nInserted" : 1 })
> db.class1.find()
{ "_id" : ObjectId("5b5304cdcf01890d9630ce8b"), "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "_id" : ObjectId("5b5304e0cf01890d9630ce8c"), "name" : "lili", "age" : 19, "sex" : "w" }
{ "_id" : ObjectId("5b5304f4cf01890d9630ce8d"), "name" : "tom", "age" : 22, "sex" : "m" }
{ "_id" : ObjectId("5b530524cf01890d9630ce8e"), "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 22, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
>
>
>
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 22, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'tom'},{$inc:{age:1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 23, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'tom'},{$inc:{age:-1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 22, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'tom'},{$inc:{age:2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'xiaoming'}{$mul:{age:0.5}})
2018-07-21T18:09:13.646+0800 E QUERY    [js] SyntaxError: missing ) after argument list @(shell):1:34
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'xiaoming'},{$mul:{age:0.5}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 10.5, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'xiaoming'},{$mul:{age:1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 10.5, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'xiaoming'},{$mul:{age:2}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 20, "sex" : "w" }
> db.class1.update({name:'ailee''},{$min:{age:18}},false,ture)
2018-07-21T18:14:51.951+0800 E QUERY    [js] SyntaxError: unterminated string literal @(shell):1:30
> db.class1.update({name:'ailee'},{$min:{age:18}},false,ture)
2018-07-21T18:15:24.550+0800 E QUERY    [js] ReferenceError: ture is not defined :
@(shell):1:40
> db.class1.update({name:'ailee'},{$min:{age:18}},false,true)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.update({name:'w'},{$min:{age:19}},false,true)
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.update({name:'w'},{$min:{age:20}},false,true)
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.update({sex:'w'},{$min:{age:19}},false,true)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 0 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 19, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.update({sex:'w'},{$min:{age:18}},false,true)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 18, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.update({name:'lili'},{$max:{age:21}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 21, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
>
View Code

 

修改操作符

$set 
修改一个域的值,或者增加一个域

e.g. 
db.class1.update({},{$set:{sex:'w'}},false,true)

e.g.
db.class1.update({name:'Abby'},{$set:{age:19,sex:'m'}})

$unset
删除一个域

e.g. 删除sex域   (后面数字0或1都表示删除)
db.class1.update({name:'Abby'},{$unset:{sex:0}})

$rename
修改域名

e.g. 将所有的sex域名改为gender
db.class1.update({},{$rename:{sex:'gender'}},false,true)

$setOnInsert 
如果第三个参数为true 并且插入新的文档,则作为插入补充内容

e.g.  如果插入了新的文档则将setOnInsert中的内容也       插入到文档中
db.class1.update({name:'Jame'},{$set:{age:19},$setOnInsert:{gender:'m','tel':"12345"}},true)

* update参数中可以写多个修改器

$inc 
加减修改器

e.g.  年龄加1 
db.class1.update({name:'Abby'},{$inc:{age:1}})
* 操作数可以是正数负数小数

$mul
乘法修改器

e.g. 将年龄乘以0.5
db.class1.update({name:'Jame'},{$mul:{age:0.5}})
* 操作数可以是正数负数小数

$min  
如果筛选的文档指定的值小于min则不修改,如果大于min给定的值则修改为min值

e.g.
db.class1.update({gender:'w'},{$min:{age:19}},false,true)

$max
如果筛选的文档指定域的值大于max值则不变,小于max值则修改为max值

e.g. 
db.class1.update({name:'Jame'},{$max:{age:20}})
View Code

 

数组修改器

$push   向数组中添加一项;

$pushAll  向数组中添加多项;

$pull    从数组中删除一项;

$pullAll  从数组中删除多项;

$each   对多个值进行逐一操作;

$position  指定插入位置;

$sort      对数组进行排序

$pop  弹出一项,值为-1 表示弹出第一项, 1 表示弹出最后一项;

$addToSet   向数组中添加一项,不能和其他的项重复;(如果原数组中没有5则添加,有则不做修改)

> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "match", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "English", "chinese" ] }
> db.class0.update({name:'ailee'},{$push:{learn:'match'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "match", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "English", "chinese", "match" ] }
####
> db.class0.update({name:'tom'},{$push:{learn:{$each:['linux','unix']}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "English", "linux", "unix" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "English", "chinese", "match" ] }
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "English", "linux", "unix" ] }
{ "name" : "ailee", "learn" : [ "English", "chinese", "match" ] }
> db.class0.update({name:'tom'},{$push:{learn:{$each:['shell'],$position:1}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "English", "shell", "linux", "unix" ] }
{ "name" : "ailee", "learn" : [ "English", "chinese", "match" ] }
>

#################
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "English", "shell", "linux", "unix" ] }
{ "name" : "ailee", "learn" : [ "English", "chinese", "match" ] }
> db.class0.update({name:'tom'},{$push:{learn:{$each:[],$sort:1}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "English", "linux", "shell", "unix" ] }
{ "name" : "ailee", "learn" : [ "English", "chinese", "match" ] }
> db.class0.update({name:'tom'},{$push:{learn:{$each:[],$sort:-1}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "learn" : [ "English", "chinese", "match" ] }
>

######
> db.class0.update({name:'ailee'},{$pop:{learn:1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" :
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chin
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "unix", "shell", "linux", "Eng
{ "name" : "ailee", "learn" : [ "English", "chinese" ] }
> db.class0.find({},{_id:0,name:1,learn:-1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chin
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "unix", "shell", "linux", "Eng
{ "name" : "ailee", "learn" : [ "English", "chinese" ] }
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chin
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "unix", "shell", "linux", "Eng
{ "name" : "ailee", "learn" : [ "English", "chinese" ] }
> db.class0.update({name:'ailee'},{$pop:{learn:-1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" :
> db.class0.find({},{_id:0,name:1,learn:1})
{ "name" : "xiaoming", "learn" : [ "match", "English", "chin
{ "name" : "lili", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "learn" : [ "unix", "shell", "linux", "Eng
{ "name" : "ailee", "learn" : [ "chinese" ] }
>
View Code

 

数组修改器

$push  向数组中添加一项
e.g.
db.class2.update({name:'小刚'},{$push:{score:10}})

$pushAll  向数组中添加多项
e.g.
db.class2.update({name:'小明'},{$pushAll:{score:[10,5]}})

$pull 从数组中删除一项
e.g.
db.class2.update({name:'小红'},{$pull:{score:'78'}})

$pullAll  从数组中删除多项
e.g.
db.class2.update({name:'小明'},{$pullAll:{score:[10,5]}})

$each   对多个值进行逐一操作

e.g. 
db.class2.update({name:'小明'},{$push:{score:{$each:[10,5]}}})

$position  指定插入位置
e.g. 需要搭配each使用,插入到1号位置
db.class2.update({name:'小红'},
{$push:{score:{$each:[78],$position:1}}})

$sort  对数组进行排序

e.g.  和each一起使用,对score数组升序排序
db.class2.update({name:'小明'},
{$push:{score:{$each:[],$sort:1}}})

$pop  弹出一项

e.g.  值为-1表示弹出第一项 1 表示弹出最后一项 
db.class2.update({name:'小明'},{$pop:{score:1}})

$addToSet  向数组中添加一项,不能和其他的项重复

e.g.  如果原数组中没有5则添加,有则不做修改
db.class2.update({name:'小明'},{$addToSet:{score:5}})
View Code

 时间类型

mongo中存储事件格式:ISODate()

方法1: new Date()   自动生成当前时间
db.class0.insert({title:'Python入门',date:new Date()})

方法2: ISODate()  生成当前时间
db.class0.insert({title:'Python精通',date:ISODate()})

方法3: Date()  将生成的当前时间变为字符串
db.class0.insert({title:'Python疯狂',date:Date()})

ISODate()
功能:生成mongo时间存储类型
参数:参数为指定时间
      “2018-1-1 12:10:34”
            “20180101 12:10:34”
            "20181102"

e.g.
db.class0.insert({title:'Python崩溃',date:ISODate("2018-11-12 11:23:32")})

时间戳

valueof()
将当前时间生成为时间戳

e.g.  
db.class0.insert({title:'Python放生',date:ISODate().valueOf()})

> db.class0.insert({title:'python',date:new Date()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0,name:1})
{ "name" : "xiaoming" }
{ "name" : "lili" }
{ "name" : "tom" }
{ "name" : "ailee" }
{  }
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
>
####
> db.class0.insert({title:'python精通',date:ISODate()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z") }
> db.class0.insert({title:'python疯狂',date:Date()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z") }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:00 GMT+0800 (CST)" }
> db.class0.insert({title:'python仿生',date:ISODate().valueOf()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z") }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:00 GMT+0800 (CST)" }
{ "title" : "python仿生", "date" : 1532174439187 }
>
View Code
> db.class0.insert({title:'python',date:new Date()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0,name:1})
{ "name" : "xiaoming" }
{ "name" : "lili" }
{ "name" : "tom" }
{ "name" : "ailee" }
{  }
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
>
####
> db.class0.insert({title:'python精通',date:ISODate()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z") }
> db.class0.insert({title:'python疯狂',date:Date()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z") }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:00 GMT+0800 (CST)" }
> db.class0.insert({title:'python仿生',date:ISODate().valueOf()})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "unix", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z") }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:00 GMT+0800 (CST)" }
{ "title" : "python仿生", "date" : 1532174439187 }
>
View Code

 

 

null

1,如果某个域存在,却没有值,可以设置为null ;

e.g.  
db.class0.insert({title:'Python 爬虫',price:null})

2. 某个域不存在,可以使用null来匹配

e.g.  当gender域不存在时可以找到这个文档
db.class1.find({gender:null},{_id:0})

> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 21, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.insert({title:'python',price:null})
WriteResult({ "nInserted" : 1 })
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 21, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
{ "title" : "python", "price" : null }
> db.class1.find({hello:null},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 21, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
{ "title" : "python", "price" : null }
>
View Code

 

 

Object  内部文档

文档内某个域的值还是一个文档则这个文档为内部文档

* 当需要使用内部文档某个域时,可以使用外部文档 .   引用内部文档的方式。但是注意在使用时需要加引号

e.g. db.class3.find({'book2.title':'Css3'},{_id:0})

e.g.
db.class3.update({'book3.title':'JavaScript'},{$set:{'book3.price':38.8}})

数组的下标引用

使用数组时,可以使用数组域 . 数组序列下标的方式使用数组中的具体某一个元素

e.g.  修改数组中的第0项
db.class2.update({name:"小明"},{$set:{'score.0':15}})

e.g. 通过数组中的第0项查找
db.class2.find({'score.0':15},{_id:0})


查找结果的有序性

即可以对find查找结果使用[]引用序列下标的方式获取查找结果的第几项

e.g.   db.class2.find({},{_id:0})[3]

> db
stu
> db.book.insert({'python':{'title':'python web','price':50.8,'page':800}})
WriteResult({ "nInserted" : 1 })
> db.book.insert({'java':{'title':'java_test','price':60.5,'page':733}})
WriteResult({ "nInserted" : 1 })
> db.book.find({},{_id:0})
{ "python" : { "title" : "python web", "price" : 50.8, "page" : 800 } }
{ "java" : { "title" : "java_test", "price" : 60.5, "page" : 733 } }
> db.book.find({'python.title':'python web'},{_id:0})
{ "python" : { "title" : "python web", "price" : 50.8, "page" : 800 } }
> db.book.update({'java.title':'java_test'},{$set:{'java.price':55.6}})

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.book.find({},{_id:0})
{ "python" : { "title" : "python web", "price" : 50.8, "page" : 800 } }
{ "java" : { "title" : "java_test", "price" : 55.6, "page" : 733 } }
>
View Code

 

练习:

1. 将小红年龄修改为8岁,兴趣爱好变为跳舞 画画 :{$set{age:8, hobby:['dance','draw']}}

2. 追加小明的兴趣 爱好 唱歌;   {$push:{hobby:['sing']}}

3. 小王兴趣爱好多了 吹牛,打篮球; {$pushAll :{hobby:{'催眠',‘打的’}}}

4. 小李兴趣多了跑步和唱歌,但是要确保不和之前的兴 趣重复;  {$addToSet:{hobby:{$each:['running','sing']}}}

5. 该班所有同学年龄加1; update({},{$inc:{age:1}},false,true)

6. 删除小明的sex属性;  {$unset:{sex:0}}

7. 删除小李的兴趣中的第一项;{$pop:{hobby:-1}}

8. 删除小红兴趣中画画和唱歌; {$pushAll:{'draw','sing'}}

 

索引

定义:指建立指定键值及所在文档中存储位置的对照清单。 使用索引可以方便我们快速进行查找,减少遍历次数,提高查找效率;

mongo如何创建索引;

ensureIndex()

功能: 创建索引

参数: 索引域, 提供索引类别, 索引选项;

(1)创建索引: ensureIndex()

  例:根据name域创建索引  : db.class2.ensureIndex({'name':1})

  注: 1表示正向索引,-1表示逆向索引

 

(2)查看当前集合索引: db.class2.getIndexes()

注:_id 域是系统自动为集合创建的索引;

(3)创建复合索引(同时根据多个域创建索引)

> db.class3.ensureIndex({name:1,age:1})

(4)删除索引: db.collection_name.dropIndex()

dropIndex()
功能:删除索引
参数:要删除的索引,可以是索引名称或者索引键值对

注:_id 索引是不会删除的

 db.class1.dropIndex({name:1})

e.g.   db.class1.dropIndex('myIndex')

(5)dropIndexes()

功能:删除所有索引

删除所有索引但是不会删除_id索引

db.class1.dropIndexes()

(6) explain(): 显示详细的查找操作信息;

db.class1.find({name:'aaa'},{_id:0}).explain()

> db.class2.dropIndex({name:1})
{ "nIndexesWas" : 2, "ok" : 1 }
> db.class2.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "stu.class2"
        }
]
> db.class2.dropIndex({_id:1})
{
        "ok" : 0,
        "errmsg" : "cannot drop _id index",
        "code" : 72,
        "codeName" : "InvalidOptions"
}
> db.class3.drop
db.class3.drop(         db.class3.dropIndexes(
db.class3.dropIndex(
> db.class3.dropIndex({name:1,age:1})
{ "nIndexesWas" : 2, "ok" : 1 }
> db.class3.getIndex
db.class3.getIndexKeys(   db.class3.getIndexes(
db.class3.getIndexSpecs(
> db.class3.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "stu.class3"
        }
]
> db.class3.ensureIndex({name:1,age:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.class3.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "stu.class3"
        },
        {
                "v" : 2,
                "key" : {
                        "name" : 1,
                        "age" : 1
                },
                "name" : "name_1_age_1",
                "ns" : "stu.class3"
        }
]
> db.class3.drop()
db.class3.drop(         db.class3.dropIndexes(
db.class3.dropIndex(
> db.class3.dropIndexes()
{
        "nIndexesWas" : 2,
        "msg" : "non-_id indexes dropped for collection",
        "ok" : 1
}
> db.class3.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "stu.class3"
        }
]
> db.class
db.class0  db.class1  db.class2  db.class3
> db.class0.find({}.{_id:0})
2018-07-21T21:39:22.724+0800 E QUERY    [js] SyntaxError: missing name                       after . operator @(shell):1:18
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "E                      nglish", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chine                      se" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "sun", "shell",                       "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z")                       }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:00 GMT+0800 (                      CST)" }
{ "title" : "python仿生", "date" : 1532174439187 }
> db.class0.find({name:'tom'},{_id:0}).explain()
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "stu.class0",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "name" : {
                                "$eq" : "tom"
                        }
                },
                "winningPlan" : {
                        "stage" : "PROJECTION",
                        "transformBy" : {
                                "_id" : 0
                        },
                        "inputStage" : {
                                "stage" : "COLLSCAN",
                                "filter" : {
                                        "name" : {
                                                "$eq" : "tom"
                                        }
                                },
                                "direction" : "forward"
                        }
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "shenzhen.com",
                "port" : 27017,
                "version" : "4.0.0",
                "gitVersion" : "3b07af3d4f471ae89e8186d33bbb1d5259597d5                      1"
        },
        "ok" : 1
}
> db.class0.ensureIndex({name:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.class0.find({name:'tom'},{_id:0}).explain()
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "stu.class0",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "name" : {
                                "$eq" : "tom"
                        }
                },
                "winningPlan" : {
                        "stage" : "PROJECTION",
                        "transformBy" : {
                                "_id" : 0
                        },
                        "inputStage" : {
                                "stage" : "FETCH",
                                "inputStage" : {
                                        "stage" : "IXSCAN",
                                        "keyPattern" : {
                                                "name" : 1
                                        },
                                        "indexName" : "name_1",
                                        "isMultiKey" : false,
                                        "multiKeyPaths" : {
                                                "name" : [ ]
                                        },
                                        "isUnique" : false,
                                        "isSparse" : false,
                                        "isPa
                                        "inde
                                        "dire
                                        "inde

                                                                                             m\"]"

                                        }
                                }
                        }
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "shenzhen.com",
                "port" : 27017,
                "version" : "4.0.0",
                "gitVersion" : "3b07af3d4f471                                                1"
        },
        "ok" : 1
}
>
View Code

 

 

(7)数组索引:

定义: 如果某个域的值为数组文档的的域创建索引,则通过数组文档进行查找时也是索引查找;

db.class1.find({hobby:'run'},{_id:0}).explain()

> db.class0.ensureIndex({learn:1})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [                                   "match", "English", "chinese" ] }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "ma                                  tch", "chinese" ] }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "sun                                  ", "shell", "linux", "English" ] }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "c                                  hinese" ] }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15                                  .709Z") }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:5                                  6:35.156Z") }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:0                                  0 GMT+0800 (CST)" }
{ "title" : "python仿生", "date" : 1532174439187 }
> db.class0.find({learn:'sun'},{_id:0}).explain()
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "stu.class0",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "learn" : {
                                "$eq" : "sun"
                        }
                },
                "winningPlan" : {
                        "stage" : "PROJECTION",
                        "transformBy" : {
                                "_id" : 0
                        },
                        "inputStage" : {
                                "stage" : "FETCH",
                                "inputStage" : {
                                        "stage" : "IXSCAN",
                                        "keyPattern" : {
                                                "learn" : 1
                                        },
                                        "indexName" : "lear                                  n_1",
                                        "isMultiKey" : true                                  ,
                                        "multiKeyPaths" : {
                                                "learn" : [
                                                        "le                                  arn"
                                                ]
                                        },
                                        "isUnique" : false,
                                        "isSparse" : false,
                                        "isPartial" : false                                  ,
                                        "indexVersion" : 2,
                                        "direction" : "forw                                  ard",
                                        "indexBounds" : {
                                                "learn" : [
                                                        "[\                                  "sun\", \"sun\"]"
                                                ]
                                        }
                                }
                        }
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "shenzhen.com",
                "port" : 27017,
                "version" : "4.0.0",
                "gitVersion" : "3b07af3d4f471ae89e8186d33bb                                  b1d5259597d51"
        },
        "ok" : 1
}
> db.class0.find({learn:'sun'},{_id:0}).explain()
{
        "queryPlanner" : {
                "plannerVersion" : 1,
                "namespace" : "stu.class0",
                "indexFilterSet" : false,
                "parsedQuery" : {
                        "learn" : {
                                "$eq" : "sun"
                        }
                },
                "winningPlan" : {
                        "stage" : "PROJECTION",
                        "transformBy" : {
                                "_id" : 0
                        },
                        "inputStage" : {
                                "stage" : "FETCH",
                                "inputStage" : {
                                        "stage" : "IXSCAN",
                                        "keyPattern" : {
                                                "learn" : 1
                                        },
                                        "indexName" : "learn_1",
                                        "isMultiKey" : true,
                                        "multiKeyPaths" : {
                                                "learn" : [
                                                        "learn"
                                                ]
                                        },
                                        "isUnique" : false,
                                        "isSparse" : false,
                                        "isPartial" : false,
                                        "indexVersion" : 2,
                                        "direction" : "forward",
                                        "indexBounds" : {
                                                "learn" : [
                                                        "[\"sun\", \"sun\"]"
                                                ]
                                        }
                                }
                        }
                },
                "rejectedPlans" : [ ]
        },
        "serverInfo" : {
                "host" : "shenzhen.com",
                "port" : 27017,
                "version" : "4.0.0",
                "gitVersion" : "3b07af3d4f471ae89e8186d33bbb1d5259597d51"
        },
        "ok" : 1
}
>
View Code

 

 

(8)子文档索引:

某个域值为文档,对其子文档创建索引,则加快通过子文档进行查找的查找速度;

db.class1.ensureIndex({'python.price':1})

 

(9)唯一索引:

定义:创建时,希望创建索引的域有不同的值,也可以通过这个方法来限制域的值;

db.class1.ensureIndex({name:1},{'unique':true})

> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 21, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
{ "title" : "python", "price" : null }
> db.class1.dropIndexes()
{
        "nIndexesWas" : 1,
        "msg" : "non-_id indexes dropped for collection",
        "ok" : 1
}
> db.class1.ensureIndex({name:1},{'unique':true})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
>
####
> db.class1.ensureIndex({age:1},{'unique':true})
{
        "ok" : 0,
        "errmsg" : "E11000 duplicate key error collection: stu.class1 index: age_1 dup key: { : 21.0 }",
        "code" : 11000,
        "codeName" : "DuplicateKey"
}
>
View Code

 

创建索引时指定域的值不能有重复,创建后插入也不允许插入重复的值;

 

(10)覆盖索引:(针对查找方式是说明)

定义:查找时,只获取索引项的内容,而不去链接其他文档的内容,这样从索引表就可以得到查找的结果,提高了查询效果;

 db.class1.find({name:'tom'},{_id:0,name:1})

(11)稀疏索引(间隙索引)

只针对有指定域的文档创建索引表,如果某个文档没有该域则不会在索引表中插入内容;

 db.class0.ensureIndex({age:1},{sparse:true})
注:对没有xx域的文档不做索引处理;

 

(12)文本索引

使用文本索引可以快速进行文本检索,这在较长的字符串搜索中比较有用;

 a,创建文本索引: db.class2.ensureIndex({msg:'text',description:'text'})
 b,通过单词进行搜索索引:db.class2.find({$text:{$search:'beautiful'}})
(多个单词用空格隔开,如果有其中任意一个单词就会被搜索)
 c, 搜索包含空格的语句,要用转义字符;  db.class2.find({$text:{$search:'\'very beautiful\''}},{_id:0})

> db.class2.find({},{_id:0})
{ "name" : "beijing", "msg" : "This is a big city and this is a very old city." }
{ "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
>
> db.class2.find({},{_id:0})
{ "name" : "beijing", "msg" : "This is a big city and this is a very old city." }
{ "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
> db.class2.ensureIndex({msg:'text',description:'text'})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}
> db.class2.find({$text:{$search:'beautiful'}})
{ "_id" : ObjectId("5b53473dcf01890d9630ce9b"), "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
> db.class2.find({$text:{$search:'beautiful'}},{_id:0})
{ "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
> db.class2.find({$text:{$search:'This'}},{_id:0})
> db.class2.find({$text:{$search:'This'}})
> db.class2.find({$text:{$search:'The'}})
> db.class2.find({$text:{$search:'old'}})
{ "_id" : ObjectId("5b53473dcf01890d9630ce9b"), "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
{ "_id" : ObjectId("5b534701cf01890d9630ce9a"), "name" : "beijing", "msg" : "This is a big city and this is a very old city." }
> db.class2.find({$text:{$search:'very beautiful'}})
{ "_id" : ObjectId("5b53473dcf01890d9630ce9b"), "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
> db.class2.find({$text:{$search:'old city'}})
{ "_id" : ObjectId("5b53473dcf01890d9630ce9b"), "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
{ "_id" : ObjectId("5b534701cf01890d9630ce9a"), "name" : "beijing", "msg" : "This is a big city and this is a very old city." }
> db.class2.find({$text:{$search:'\'very beautiful\''}},{_id:0})
{ "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
> db.class2.find({$text:{$search:'\'city is\''}},{_id:0})
{ "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
{ "name" : "beijing", "msg" : "This is a big city and this is a very old city." }
>
View Code

 

d, 搜索某个单词,并且不包含某个单词;(减号 -)

> db.class2.find({$text:{$search:'city -big'}},{_id:0})
e, 删除文本索引;

通过getIndexes() ,查看索引名称

通过dropIndex(),删除

> db.class2.find({$text:{$search:'city -big'}},{_id:0})
{ "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
> db.class2.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "stu.class2"
        },
        {
                "v" : 2,
                "key" : {
                        "_fts" : "text",
                        "_ftsx" : 1
                },
                "name" : "msg_text_description_text",
                "ns" : "stu.class2",
                "weights" : {
                        "description" : 1,
                        "msg" : 1
                },
                "default_language" : "english",
                "language_override" : "language",
                "textIndexVersion" : 3
        }
]
> db.class2.dropIndex('msg_text_description_text')
{ "nIndexesWas" : 2, "ok" : 1 }
> db.class2.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "stu.class2"
        }
]
>
View Code

 

 

索引约束;

1,当数据库进行大量查找操作时,可以进行索引;而不是修改操作;

  影响插入、删除 、修改数据的效率;当数据发生修改时,索引必须同步更新;

2,索引表也需要占用一定空间,所以,当数据量比较小时不适宜创建索引;

  总结: 并不是所有情况下都适合创建索引或者创建大量索引;

 

固定集合;

MongoDB中可以创建大小固定的集合,称为固定集合,固定集合性能出色且适宜于很多场景;

比如:日志处理, 临时缓存;

特点:插入输入快;  顺序查询速度快; 能够淘汰早期的数据;

创建固定集合: db.createCollection(collectionname,{capped:true, size:1000, max:1000})

size:表示设置固定集合的大小, 单位kb;

max:表示固定集合中最多存放多少条文档;

> db.createCollection('log',{capped:true,size:1000,max:3})
{ "ok" : 1 }
> db.log.insert({pid:6666,cpu:0.05})
WriteResult({ "nInserted" : 1 })
> db.log.insert({pid:7777,cpu:0.17})
WriteResult({ "nInserted" : 1 })
> db.log.insert({pid:8888,cpu:0.19})
WriteResult({ "nInserted" : 1 })
> db.log.find({},{_id:0})
{ "pid" : 6666, "cpu" : 0.05 }
{ "pid" : 7777, "cpu" : 0.17 }
{ "pid" : 8888, "cpu" : 0.19 }
> db.log.insert({pid:9999,cpu:0.12})
WriteResult({ "nInserted" : 1 })
> db.log.find({},{_id:0})
{ "pid" : 7777, "cpu" : 0.17 }
{ "pid" : 8888, "cpu" : 0.19 }
{ "pid" : 9999, "cpu" : 0.12 }
>
View Code

 

 

聚合:

对数据文档进行整理统计;(更高级的查找)

db.collection_name.aggregate()

功能:聚合函数,配合聚合条件进行数据整理;

聚合操作符:

$group  分组; 按照什么分组由具体的分组操作符而定;

> db.class1.aggregate({$group:{_id:'$sex',num:{$sum:1}}})
                   统计聚合       分组      按照哪个域分组, 统计结果域名

$sum    求和

> db.class1.aggregate({$group:{_id:'$sex',num:{$sum:'$age'}}})
$avg  求平均数

> db.class1.aggregate({$group:{_id:'$sex',num:{$avg:'$age'}}})
$min   求最小值

> db.class1.aggregate({$group:{_id:'$sex',num:{$min:'$age'}}})
$max  求最大值

> db.class1.aggregate({$group:{_id:'$sex',num:{$max:'$age'}}})
$first  第一个文档的指定值

 db.class1.aggregate({$group:{_id:'$sex',name:{$first:'$name'}}})

$last  最后一个文档的指定值

 db.class1.aggregate({$group:{_id:'$sex',name:{$last:'$name'}}})

++++++++++++++++++++++++++

$project   用于修饰的文档的显示效果;

值同find的第二个参数相同

db.class1.aggregate({$project:{_id:0,Name:'$name',Age:'$age'}})  可以改变显示的域名

$match   过滤数据

值和qurey 部分一样;

db.class1.aggregate($match:{age:18})

$limit  显示前几条数据;值为一个正数

db.class1.aggregate({$limit:3})

 

$skip  跳过几条数据;值为一个正数

db.class1.aggregate({$skip:3})

$sort  排序

db.class1.aggregate({$sort:{age:1}})

> show collections
book
class0
class1
class2
class3
log
> db.class2.find({},{_id:0})
{ "name" : "beijing", "msg" : "This is a big city and this is a very old city." }
{ "name" : "nanjing", "msg" : "The city is very beautiful, and this is a very old city." }
> db.class1.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "lili", "age" : 21, "sex" : "w" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
{ "title" : "python", "price" : null }
>
>
> db.class1.aggregate({$group:{_id:'$sex',num:{$sum:1}}})
{ "_id" : null, "num" : 1 }
{ "_id" : "w", "num" : 2 }
{ "_id" : "m", "num" : 2 }
> db.class1.aggregate({$group:{_id:'$sex',num:{$sum:'$age'}}})
{ "_id" : null, "num" : 0 }
{ "_id" : "w", "num" : 39 }
{ "_id" : "m", "num" : 45 }
> db.class1.aggregate({$group:{_id:'$sex',num:{$avg:'$age'}}})
{ "_id" : null, "num" : null }
{ "_id" : "w", "num" : 19.5 }
{ "_id" : "m", "num" : 22.5 }
> db.class1.aggregate({$group:{_id:'$sex',num:{$min:'$age'}}})
{ "_id" : null, "num" : null }
{ "_id" : "w", "num" : 18 }
{ "_id" : "m", "num" : 21 }
> db.class1.aggregate({$group:{_id:'$sex',num:{$max:'$age'}}})
{ "_id" : null, "num" : null }
{ "_id" : "w", "num" : 21 }
{ "_id" : "m", "num" : 24 }
> db.class1.aggregate({$group:{_id:'$sex',name:{$first:'$name'}}})
{ "_id" : null, "name" : null }
{ "_id" : "w", "name" : "lili" }
{ "_id" : "m", "name" : "xiaoming" }
> db.class1.aggregate({$group:{_id:'$sex',name:{$last:'$name'}}})
{ "_id" : null, "name" : null }
{ "_id" : "w", "name" : "ailee" }
{ "_id" : "m", "name" : "tom" }
> db.class1.aggregate({$project:{_id:0,name:1,age:1}})
{ "name" : "xiaoming", "age" : 21 }
{ "name" : "lili", "age" : 21 }
{ "name" : "tom", "age" : 24 }
{ "name" : "ailee", "age" : 18 }
{  }
> db.class1.aggregate({$project:{_id:0,Name:'$name',Age:'$age'}})
{ "Name" : "xiaoming", "Age" : 21 }
{ "Name" : "lili", "Age" : 21 }
{ "Name" : "tom", "Age" : 24 }
{ "Name" : "ailee", "Age" : 18 }
{  }
> db.class1.aggregate($match:{age:18})
2018-07-22T12:59:12.123+0800 E QUERY    [js] SyntaxError: missing ) after argument list @(shell):1:26
> db.class1.aggregate({$match:{age:18}})
{ "_id" : ObjectId("5b530524cf01890d9630ce8e"), "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.aggregate({$limit:3})
{ "_id" : ObjectId("5b5304cdcf01890d9630ce8b"), "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "_id" : ObjectId("5b5304e0cf01890d9630ce8c"), "name" : "lili", "age" : 21, "sex" : "w" }
{ "_id" : ObjectId("5b5304f4cf01890d9630ce8d"), "name" : "tom", "age" : 24, "sex" : "m" }
> db.class1.aggregate({$limit:3},{_id:0})
2018-07-22T13:03:04.327+0800 E QUERY    [js] Error: command failed: {
        "ok" : 0,
        "errmsg" : "Unrecognized pipeline stage name: '_id'",
        "code" : 40324,
        "codeName" : "Location40324"
} : aggregate failed :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
doassert@src/mongo/shell/assert.js:18:14
_assertCommandWorked@src/mongo/shell/assert.js:534:17
assert.commandWorked@src/mongo/shell/assert.js:618:16
DB.prototype._runAggregate@src/mongo/shell/db.js:260:9
DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1056:12
@(shell):1:1
> db.class1.aggregate({$skip:3})
{ "_id" : ObjectId("5b530524cf01890d9630ce8e"), "name" : "ailee", "age" : 18, "sex" : "w" }
{ "_id" : ObjectId("5b532396cf01890d9630ce97"), "title" : "python", "price" : null }
> db.class1.aggregate({$sort:{age:1}})
{ "_id" : ObjectId("5b532396cf01890d9630ce97"), "title" : "python", "price" : null }
{ "_id" : ObjectId("5b530524cf01890d9630ce8e"), "name" : "ailee", "age" : 18, "sex" : "w" }
{ "_id" : ObjectId("5b5304cdcf01890d9630ce8b"), "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "_id" : ObjectId("5b5304e0cf01890d9630ce8c"), "name" : "lili", "age" : 21, "sex" : "w" }
{ "_id" : ObjectId("5b5304f4cf01890d9630ce8d"), "name" : "tom", "age" : 24, "sex" : "m" }
>
View Code

 

 

集合管道;

定义:前一个聚合操作的结果给后一个聚合操作执行;

格式: 将多个聚合操作放到一个【】中

  match  结果 ----->    sort排序--->    project 显示

 db.class1.aggregate([{$match:{sex:'m'}},{$sort:{age:1}},{$project:{_id:0}}])

db.class1.aggregate([{$match:{sex:'w'}},{$sort:{age:1}},{$project:{_id:0}}])

> db.class1.aggregate([{$match:{sex:'m'}},{$sort:{age:1}},{$project:{_id:0}}])
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
{ "name" : "tom", "age" : 24, "sex" : "m" }
> db.class1.aggregate([{$match:{sex:'w'}},{$sort:{age:1}},{$project:{_id:0}}])
{ "name" : "ailee", "age" : 18, "sex" : "w" }
{ "name" : "lili", "age" : 21, "sex" : "w" }
> db.class1.aggregate([{$match:{sex:'w'}},{$sort:{age:-1}},{$project:{_id:0}}])
{ "name" : "lili", "age" : 21, "sex" : "w" }
{ "name" : "ailee", "age" : 18, "sex" : "w" }
> db.class1.aggregate([{$match:{sex:'m'}},{$sort:{age:-1}},{$project:{_id:0}}])
{ "name" : "tom", "age" : 24, "sex" : "m" }
{ "name" : "xiaoming", "age" : 21, "sex" : "m" }
>
View Code

 

 

练习:

1,按照性别进行分组,统计每组人数;db.grade.aggregate({$group:{_id:'$sex',num:{$sum:1}}})

2,按照学生姓名分组,过滤出有重名的同学; db.class0.aggregate([{$group:{_id:'$name',num:{$sum:1}}},{$match:{num:{$gt:1}}}])

3,统计每名男生的语文分数; > db.class0.aggregate([{$match:{sex:'m'}},{$project:{_id:0,name:1,'scource.chinese':1}}])

4,将女生按照英语分数降序排列;> db.class0.aggregate([{$match:{sex:'w'}},{$sort:{'source.english':-1}}])

> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "sun", "shell", "linux", "English" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z"), "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z"), "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:00 GMT+0800 (CST)", "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python仿生", "date" : 1532174439187, "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
> db.class0.insert({name:'tom'})
WriteResult({ "nInserted" : 1 })
> db.class0.find({},{_id:0})
{ "name" : "xiaoming", "age" : 21, "sex" : "m", "learn" : [ "match", "English", "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "name" : "tom", "age" : 24, "sex" : "m", "learn" : [ "sun", "shell", "linux", "English" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python", "date" : ISODate("2018-07-21T11:50:15.709Z"), "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python精通", "date" : ISODate("2018-07-21T11:56:35.156Z"), "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python疯狂", "date" : "Sat Jul 21 2018 19:58:00 GMT+0800 (CST)", "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "title" : "python仿生", "date" : 1532174439187, "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "name" : "tom" }
> db.class0.aggregate([$group:{_id:'$name',num:{$sum:1}}])
2018-07-22T14:04:46.817+0800 E QUERY    [js] SyntaxError: missing ] after element list @(shell):1:27
> db.class0.aggregate([{$group:{_id:'$name',num:{$sum:1}}}])
{ "_id" : null, "num" : 4 }
{ "_id" : "lili", "num" : 1 }
{ "_id" : "xiaoming", "num" : 1 }
{ "_id" : "tom", "num" : 2 }
{ "_id" : "ailee", "num" : 1 }
> db.class1.aggregate([{$group:{_id:'$name',num:{$sum:1}}},{$match:{num:{$gt:1}}}])
> db.class0.aggregate([{$group:{_id:'$name',num:{$sum:1}}},{$match:{num:{$gt:1}}}])
{ "_id" : null, "num" : 4 }
{ "_id" : "tom", "num" : 2 }
> db.class0.aggregate([{$match:{sex:'m'}},{$project:{_id:0,name:1,'scource.chinese':1}}])
{ "name" : "xiaoming" }
{ "name" : "tom" }
> db.class0.aggregate([{$match:{sex:'w'}},{$sort:{'source.english':-1}}])
{ "_id" : ObjectId("5b530c47cf01890d9630ce90"), "name" : "lili", "age" : 21, "sex" : "w", "learn" : [ "match", "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
{ "_id" : ObjectId("5b530cc3cf01890d9630ce92"), "name" : "ailee", "age" : 18, "sex" : "w", "learn" : [ "chinese" ], "source" : { "chinese" : 88, "englis" : 78, "math" : 98 } }
>
View Code

 

posted on 2018-07-15 22:18  微子天明  阅读(230)  评论(0编辑  收藏  举报

导航