MongoDB - 2

时间:2022-05-10 20:13:35

Aggregation Framework:

MongoDB - 2

$project:

a document stream by renaming, adding, or removing fields

#alter Data
db[:zips].find.aggregate([{:$project => {:_id=> 1, :city=> {:$toLower => '$city'}}}]).each {|r| pp r}

$group:

db[:zips].find.aggregate([{:$group => {:_id => '$state', :population => {:$sum => '$pop'}}}]).each {|r| pp r}

#max
db[:zips].find.aggregate([{:$group => {:_id => '$state', :max_zip=> {:$max=> '$pop'}}}]).each {|r| pp r} #min
db[:zips].find.aggregate([{:$group => {:_id => '$state', :min_zip=> {:$min=> '$pop'}}}]).each {|r| pp r} #push - return array of all values...
db[:zips].find.aggregate([{:$group => {:_id => '$state', :zips=> {:$push=> '$_id'}}}]).each {|r| pp r} #addToSet - return array of all value no duplicate
db[:zips].find.aggregate([{:$group => {:_id => '$state', :zips=> {:$addToSet=> '$_id'}}}]).each {|r| pp r}

$match:

$unwind:

#unwind return one document 

db[:zips].find().aggregate([{:$match => {:city=>'ELMIRA'},group=>{:_id=>{:city=>'$city',:state=>'$state'},:zips=>{:addToSet=>'$_id'}}},{:$unwind=>'$zips'}]).each {|r| pp r}