Loading

mongo去重统计

表名:parkUserCost
id:
patkId:
userId:
phone:
costVal:

适合特定条件下,对某些字段进行去重筛选。(比如限定抢购)

第一种,使用\(first操作符。\)first 会把数组的第一个元素取出,作为一个对象。

// 第一种(可转java版本)
db.getCollection('parkUserCost').aggregate([
   {"$match" : {
      "$and" : [
          // {"name" : "1640"} // 筛选条件
           ]
           }
        },
    {"$group" : {
        "_id" : "$phone",
        "val" : {"$first" :  "$costVal" },
        }},
    {"$group" : {
         "_id" : {},
        "totalVal" :{"$sum" : "$val"}
         }}
])

第二种,使用$slice操作符。从数组的第几个开始,截取几个,保存到数组

// 第二种
db.getCollection('parkUserCost').aggregate([
   {"$match" : {
      "$and" : [
          // {"name" : "1640"} // 筛选条件
           ]
           }
        },
    {"$group" : {
        "_id" : "$phone",
        "val" : {"$push" :  "$costVal" },
        }},
    {"$project" : {
         "val" :{"$sum" :{"$slice" : ["$val", 0, 1 ] }}
        }},
    {"$group" : {
         "_id" : {},
        "totalVal" :{"$sum" : "$val"}
         }}
])

第三种,使用$arrayElemAt,返回数组的第几个元素。序号的循环的,最后一个使用-1

// 第三种
db.getCollection('parkUserCost').aggregate([
   {"$match" : {
      "$and" : [
          // {"name" : "1640"} // 筛选条件
           ]
           }
        },
    {"$group" : {
        "_id" : "$phone",
        "val" : {"$push" :  "$costVal" },
        }},
    {"$project" : {
        "val" :  { "$arrayElemAt" :[ "$val" , 0] }
        }},
    {"$group" : {
         "_id" : {},
        "totalVal" :{"$sum" : "$val"}
         }}
])

若要表中的全部字段,可使用$$ROOT获取

db.getCollection('parkUserCost').aggregate([
   {"$match" : {
      "$and" : [
          // {"name" : "1640"} // 筛选条件
           ]
           }
        },
    {"$group" : {
        "_id" : "$phone",
        "item": {"$first": "$$ROOT"},
        "val" : {"$first" :  "$costVal" },
        }},
])

http://www.runoob.com/mongodb/mongodb-tutorial.html

posted @ 2017-11-10 10:50  遗失的拂晓  阅读(848)  评论(0编辑  收藏  举报