Mongodb 常见操作符

$gt   大于
$lt    小于
$gte  大于等于
$lte   小于等于
$ne   不等于

聚合查询操作符:

$project

db.test.aggregate(
    { $project : {
         _id : 0 ,
        name : 1  ,
        weight : 1 ,
        newWeight : "$weight"
    }}
 );

上面表示查询name和weight字段,不显示id值。并把weight重命名为newWeight

 

$match

db.test.aggregate([
    {$match : 
        { weight : 
            { $gte : 0.5, $lte : 1 } 
        }
    },
    { $group: 
        { _id: null, 
          count: { $sum: 1 } 
        } 
    }
]);

查询weight在0.5到1之间的数据,再在$group管道操作符中进行处理

 

$limit

db.test.aggregate({ $limit : 5 });

返回前n条数据

 

$skip

db.test.aggregate({ $skip: 5 });

查询前n条数据之后的数据

 

$cond

           discount:
           {
             $cond: { if: { $gte: [ "$qty", 250 ] }, then: 30, else: 20 }
           }

表情况,可以跟if then连用。

 

$sum

表求和

$sum:1表示每个分组的个数,$sum:$字段  表示每个分组该字段的和

比如存在:

{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }

使用:

db.sales.aggregate(
 [
  {
  $group:
   {
   _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
   totalAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
   count: { $sum: 1 }
   }
  }
 ]
)

可以得到:

{ "_id" : { "day" : 46, "year" : 2014 }, "totalAmount" : 150, "count" : 2 }
{ "_id" : { "day" : 34, "year" : 2014 }, "totalAmount" : 45, "count" : 2 }
{ "_id" : { "day" : 1, "year" : 2014 }, "totalAmount" : 20, "count" : 1 }

 

posted @ 2021-07-09 17:52  RookieCoderAdu  阅读(141)  评论(0)    收藏  举报