it_worker365

   ::  ::  ::  ::  :: 管理

官网操作手册,基本就够用

https://docs.mongodb.com/manual/

下面是个分组查询的例子,项目中用到然后查了个例子,自己理解了下,觉得很好很强大。

https://blog.csdn.net/yown/article/details/53946781

Mongo分组查询,分组查询,collection为要查询的集合,keyf为定义的聚合key或者有返回值的函数,query为查询条件,initial为各个字段的初始化方法,reduce为计算迭代的函数,finalz为完成查询后的打扫方法,一般删除集合之类的,利用脚本语言,可以实现多种聚合方式的查询

GroupCommand cmd = new GroupCommand(collection, keyf, query, initial, reduce, finalz);

Command:

db.runCommand({group:
    {
        ns:"collection1",
        cond : { "$and":[{"gmtCreate":{"$gt":new ISODate("2016-10-01T00:00:00.000Z")}}, {"gmtCreate":{"$lt":new ISODate("2018-12-31T23:59:59.999Z")}}]},
        $keyf:function(doc){
          var myDate = new Date(doc.gmtCreate);
          var mm = '0'+(myDate.getMonth()+1); 
          var dd = '0'+myDate.getDate();
          return {day:myDate.getFullYear()+''+mm.substring(mm.length-2)+''+dd.substring(dd.length-2)};
        },
        initial:{"shareCount" : 0 , "shareUserCount" : 0 , "userIdMap" : {}},
        $reduce:function(doc, prev){ 
          if(doc.userId != null){  
            prev.shareCount ++;  
            if(prev.userIdMap[doc.userId] == null) {
              prev.shareUserCount ++;
              prev.userIdMap[doc.userId] = 1;
            }
           }
          },
        finalize: function(doc){ delete doc.userIdMap; }
    }
});

JAVA方式:

    public BasicDBList testGroupMongo(String dbName, String collectionName, BasicDBObject condition,
                                      List<String> fields)
            throws MongoDAOException {
        DB db = mongoClient.getDB(dbName);
        DBCollection collection = db.getCollection(collectionName);
        String keyf = "function(doc){" + "var myDate = new Date(doc.gmtCreate);"
                + "          var mm = '0'+(myDate.getMonth()+1); " + "          var dd = '0'+myDate.getDate();"
                + "          return {day:myDate.getFullYear()+'@'+mm.substring(mm.length-2)+'@'+dd.substring(dd.length-2)};"
                + "}";
        BasicDBObject query = new BasicDBObject(); // where条件
        BasicDBObject query1 = new BasicDBObject();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //距离现在9个月之前
        calendar.add(Calendar.MONTH, -9);
        Date start = calendar.getTime();

        query1.append("$gte", start);
        query1.append("$lte", new Date());
        query.append("gmtCreate", query1);
        String reduce = "function(doc, prev){ " + "if(doc.userId != null){  " + "  prev.shareCount++;  "
                + "  if(isNaN(prev.userIdMap[doc.userId])) { " + "      prev.shareUserCount ++;"
                + "      prev.userIdMap[doc.userId] = 1;" + "  }" + "}" + "}";
        String finalz = "function(prev){delete prev.userIdMap}";
        BasicDBObject initial = new BasicDBObject();
        initial.append("shareCount", 0);
        initial.append("shareUserCount", 0);
        initial.append("userIdMap", new HashMap<String, Integer>());
        GroupCommand cmd = new GroupCommand(collection, keyf, query, initial, reduce, finalz);
        BasicDBList group = (BasicDBList) collection.group(cmd);
        return group;
    }

命令执行例子

{
    "retval" : [
        {
            "day" : "20171023",
            "shareCount" : 2,
            "shareUserCount" : 1
        },
        {
            "day" : "20181023",
            "shareCount" : 1,
            "shareUserCount" : 1
        },
        {
            "day" : "20180223",
            "shareCount" : 1,
            "shareUserCount" : 1
        }
    ],
    "count" : NumberLong(4),
    "keys" : NumberLong(3),
    "ok" : 1
}

aggregate:

db.collection1.find({"orderId":333,"address": { $in: ["shanghai", "beijing"] }}).limit(3).skip(0)
db.getCollection('collection1').aggregate(
   [
       { $group :{
_id :
"$orderId", address: { $push: "$address" } }
}, { $match : {"orderId": 333} },{ $limit : 1 } ],{ allowDiskUse: true } ) db.getCollection('collection1').aggregate( [ { $group : { _id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } }, totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } }, averageQuantity: { $avg: "$quantity" }, count: { $sum: 1 } } } ] ) db.getCollection('collection1').aggregate( [ { $group : { _id : "$item", books: { $push: "$price" } } },{ $limit : 3 }, {$match : {"_id": "xyz"}}, { $project : { _id:1, books : 1 } } //结果中包含某些列 ] )

觉得这个也挺好用的

 

posted on 2018-09-21 10:40  it_worker365  阅读(162)  评论(0编辑  收藏  举报