数据库
首页 > 数据库> > mongodb的聚合aggregate|group|match|project|sort|limit|skip|unwind

mongodb的聚合aggregate|group|match|project|sort|limit|skip|unwind

作者:互联网

聚合 aggregate

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

  管道

ps ajx | grep mongo

表达式

表达式:'$列名'

常用表达式

$group

db.stu.aggregate([
    {$group:
        {
            _id:'$gender',
            counter:{$sum:1}
        }
    }
])

Group by null

 

db.stu.aggregate([
    {$group:
        {
            _id:null,
            counter:{$sum:1},
            avgAge:{$avg:'$age'}
        }
    }
])

透视数据

db.stu.aggregate([
    {$group:
        {
            _id:'$gender',
            name:{$push:'$name'}
        }
    }
])
db.stu.aggregate([
    {$group:
        {
            _id:'$gender',
            name:{$push:'$$ROOT'}
        }
    }
])

$match

 

db.stu.aggregate([
    {$match:{age:{$gt:20}}}
])

 

db.stu.aggregate([
    {$match:{age:{$gt:20}}},
    {$group:{_id:'$gender',counter:{$sum:1}}}
])

$project

db.stu.aggregate([
    {$project:{_id:0,name:1,age:1}}
])
db.stu.aggregate([
    {$group:{_id:'$gender',counter:{$sum:1}}},
    {$project:{_id:0,counter:1}}
])

$sort

b.stu.aggregate([{$sort:{age:1}}])
db.stu.aggregate([
    {$group:{_id:'$gender',counter:{$sum:1}}},
    {$sort:{counter:-1}}
])

$limit

db.stu.aggregate([{$limit:2}])

$skip

db.stu.aggregate([{$skip:2}])
db.stu.aggregate([
    {$group:{_id:'$gender',counter:{$sum:1}}},
    {$sort:{counter:1}},
    {$skip:1},
    {$limit:1}
])

$unwind

语法1

db.集合名称.aggregate([{$unwind:'$字段名称'}])
db.t2.insert({_id:1,item:'t-shirt',size:['S','M','L']})
db.t2.aggregate([{$unwind:'$size'}])

语法2

db.inventory.aggregate([{
    $unwind:{
        path:'$字段名称',
        preserveNullAndEmptyArrays:<boolean>#防止数据丢失
    }
}])
db.t3.insert([
{ "_id" : 1, "item" : "a", "size": [ "S", "M", "L"] },
{ "_id" : 2, "item" : "b", "size" : [ ] },
{ "_id" : 3, "item" : "c", "size": "M" },
{ "_id" : 4, "item" : "d" },
{ "_id" : 5, "item" : "e", "size" : null }
])
db.t3.aggregate([{$unwind:'$size'}])
db.t3.aggregate([{$unwind:{path:'$sizes',preserveNullAndEmptyArrays:true}}])

标签:sort,unwind,group,mongodb,db,stu,文档,aggregate,id
来源: https://www.cnblogs.com/alexzhang92/p/10479083.html