MongoDB 高级查询操作

目录

MongoDB 中写法:

AND

OR

查询子文档或数组中数据

聚合查询

语法

 $match

$project

$literal

$group

$max,$min,$sum,$avg

$last,$first

$unwind

$lookup

Python 中写法:

AND 与 OR

查询子文档或数组中数据

聚合查询


MongoDB 中写法:

AND

语法:.find({'$and' : [字典1.字典2.字典3.。。。。字典n]})

查询 age 大于 20,并且current_home 为 贵州贵阳

隐式查询:

没有关键字 AND,出现,却能表达 与 的关系

db.getCollection('people_info').find({'age':{'$gt':20},
                                      'current_home':'贵州贵阳'}
                                     )

显示查询:

db.getCollection('people_info').find({'$and':
                                      [{'age':{'$gt':20}},{'current_home':'贵州贵阳'}]
                                      })

显示,隐式混用,查询 age 大于 20,并且current_home 为 贵州贵阳,id 小于 15 的

 

OR

or 与 and 操作格式一样,只需把关键字 “$and” 换成 “$or” 即可

 

查询子文档或数组中数据

嵌入式文档名.嵌套字段名

查询 age 为 19 的数据

db.getCollection('people_indo').find({
        'user_info.age':19
    })

只返回 age 字段,不返回其他任何字段

db.getCollection('people_indo').find(
        {'user_info.age':19},
        {'_id':0,'user_info.age':1}
        )

 

查询 size 包含 M 的字段,查询不包含 M 的字段

db.getCollection('people_indo').find({'size':'M'})
db.getCollection('people_indo').find({'size':{'$ne':'M'}})

查询某个范围的写法,与 .find() 查询写法一样

$size

查询数组大小,查询大小为 3 的数组

db.getCollection('people_indo').find({'size':{'$size':3}})

索引查数据,查询第一个索引,且值为 M 的值

db.getCollection('people_indo').find({'size.0':'M'})

 

聚合查询

按一定规则对数据集进行筛选,清洗

语法

collection.aggregate([‘阶段1’,‘阶段2’。。。‘阶段N’])

有 0 个阶段,写为 collection.aggregate(),多个阶段。每个阶段为字典

 $match

语法:collection.aggregate([{'$match':{和 find 第一个参数相同}}])

查询 age 字段大于等于 20 的

从结果看与 .find() 结果一样,要配合其他关键字效果才明显

db.getCollection('people_info').aggregate([{'$match':{'age':{'$gte':20}}}])

$project

与 find 相比好处就是查询出来的字段会变成单独的字段。不会再嵌套

语法:collection.aggregate([{'$project':{字段过滤语句,和 find 第二个字段相同}}])

查询 name 与 age 字段,其他不返回,如果值为 1,就返回对应的,没有就全部返回 null

db.getCollection('people_info').aggregate([
        {'$project':{'age':1,'name':1}}
       ])

查询 age 大于 20,只返回 name,age 字段,不返回 _id

db.getCollection('people_info').aggregate([
        {'$match':{'age':{'$gt':20}}},
        {'$project':{'_id':0,'age':1,'name':1}}
       ])

添加新字段,原来是没有 hello 这个字段的

db.getCollection('people_info').aggregate([
        {'$match':{'age':{'$gt':20}}},
        {'$project':{'_id':0,'age':1,'name':1,'hello':'word'}}
       ])

复制现有字段,把 hello 字段,添加为现有字段 age 的值

db.getCollection('people_info').aggregate([
        {'$match':{'age':{'$gt':20}}},
        {'$project':{'_id':0,'age':1,'name':1,'hello':'$age'}}
       ])

修改现有字段

db.getCollection('people_info').aggregate([
        {'$match':{'age':{'$gt':20}}},
        {'$project':{'_id':0,'age':'lalala','name':1,'hello':'$age'}}
       ])

$literal

想添加一个字符串,但值就是 1,想添加一个字符串但以 $ 开头,与 $project 语法冲突了,要用 $literal

db.getCollection('people_info').aggregate([
        {'$match':{'age':{'$gt':20}}},
        {'$project':{'_id':0,'age':'lalala','name':1,'hello':{'$literal':'$nihao'},'abcd':{'literal':1}}}
       ])

 

现有数据集:

$group

自带去重功能

语法:collection.aggregate([{'$group':{'_id':'$被去重的字段'}}])

对 name 去重

db.getCollection('grades').aggregate([{'$group':{'_id':'$name'}}])

$max,$min,$sum,$avg

如果使用值为非数字字段,$sum 返回 0,$avg 返回 null,而 $mx,$min 是可以比较字符串大小的

语法:

db.getCollection('grades').aggregate([
    {'$group':
        {'_id':'$被去重字段名',
         'max_score':{'$max':'$字段名'},
         'min_score':{'$min':'$字段名'},
         'sum_score':{'$sum':'$字段名'},
         'average_score':{'$avg':'$字段名'}
        }
        
    }
   ])

计算每个人最大值,最小值,总和,平均值

$sum 的值也可以使用数字 1,就变成了统计每一个分组内有多少条记录

max_score,min_score,sum_score,average_score 是分组查询结果的新的字段名

db.getCollection('grades').aggregate([
    {'$group':
        {'_id':'$name',
         'max_score':{'$max':'$grade'},
         'min_score':{'$min':'$grade'},
         'sum_score':{'$sum':'$grade'},
         'average_score':{'$avg':'$grade'}
        }
        
    }
   ])

$last,$first

date,score 是分组查询结果的新的字段名

MongoDB 数据先到的就是老数据,后到的就是新数据,分别获取最新的一条和最老的一条

db.getCollection('grades').aggregate([
    {'$group':
        {'_id':'$name',
         'date':{'$last':'$date'},
         'score':{'$last':'$grade'}
        }
    }
   ])

$unwind

把一条包含数组的记录拆分为很多条记录,每条记录拥有数组中的一个元素,一次只能拆开一个数组,要拆开多个数组就要经历这个阶段多次,是对数组操作!

语法:collection.aggregate([{'$unwind':'$字段名'}])

$lookup

语法:

数据库.主集合.aggregate([
    {'$lookup':{
         'from':'被查集合名',
         'localField':'主集合字段',
         'foreignField':'被查集合字段',
         'as':'保存查询结果的字段名'
                }
        
     }
])

联集合查询,从两个不同集合根据某个关键字查询,新的字段是数组,可能有多条记录满足

user 集合

post 集合

在 post 集合中查询 user 的用户信息,那么主集合就是 post,被查集合就是 user

db.getCollection('post').aggregate([
    {'$lookup':{
         'from':'user',
         'localField':'user_id',
         'foreignField':'id',
         'as':'user_info'
                }
        
     }
])

优化结果:

$unwind 把数组中的嵌入式文档拆分出来后,$project 选定 content,post_time,name,work 字段

db.getCollection('post').aggregate([
    {'$lookup':{
         'from':'user',
         'localField':'user_id',
         'foreignField':'id',
         'as':'user_info'
                }
        
     },
     {'$unwind':'$user_info'},
     {
      '$project':{
          'content':1,
          'post_name':1,
          'name':'$user_info.name',
          'work':'$user_info.work'
                 }   
      }
])

$match 需要查询具体的数据,最好放在第一个流程

 

 

 

 

Python 中写法:

AND 与 OR

与在 MongoDB 中的写法一样,直接搬过去

 

查询子文档或数组中数据

与在 MongoDB 中的写法一样,直接搬过去

 

聚合查询

与在 MongoDB 中的写法一样,直接搬过去

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值