您的位置:首页 > 数据库 > Mongodb

用java连接mongodb并执行$sum和$avg结合的聚合函数的实例。

2016-07-09 10:06 543 查看
代码如下:

1、

db.sales.find({})

如下:



    "_id" : 1.0, 

    "item" : "abc", 

    "price" : 10.0, 

    "quantity" : 2.0, 

    "date" : ISODate("2014-03-01T08:00:00.000+0000")

}



    "_id" : 2.0, 

    "item" : "jkl", 

    "price" : 20.0, 

    "quantity" : 1.0, 

    "date" : ISODate("2014-03-01T09:00:00.000+0000")

}



    "_id" : 3.0, 

    "item" : "xyz", 

    "price" : 5.0, 

    "quantity" : 10.0, 

    "date" : ISODate("2014-03-15T09:00:00.000+0000")

}



    "_id" : 4.0, 

    "item" : "xyz", 

    "price" : 5.0, 

    "quantity" : 20.0, 

    "date" : ISODate("2014-04-04T11:21:39.736+0000")

}



    "_id" : 5.0, 

    "item" : "abc", 

    "price" : 10.0, 

    "quantity" : 10.0, 

    "date" : ISODate("2014-04-04T21:23:13.331+0000")

}

2、

db.sales.aggregate(

   [

      {

        $group : {

           

           _id : { month: { $month: "$date" }, day: { $dayOfMonth: "$date" }, year: { $year: "$date" } },

           totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } },

           averageQuantity: { $avg: "$quantity" },

           count: { $sum: 1 }

           

        }

      }

   ]

)

的结果如下:

{ "_id" : { "month" : 4 , "day" : 4 , "year" : 2014} , "totalPrice" : 200.0 , "averageQuantity" : 15.0 , "count" : 2}

{ "_id" : { "month" : 3 , "day" : 15 , "year" : 2014} , "totalPrice" : 50.0 , "averageQuantity" : 10.0 , "count" : 1}

{ "_id" : { "month" : 3 , "day" : 1 , "year" : 2014} , "totalPrice" : 40.0 , "averageQuantity" : 1.5 , "count" : 2}

3、

package test;

/** 

* @author : suyuyuan

* @date :2016年6月23日 下午3:10:03 

* @version 1.0 

*/

import java.net.UnknownHostException;

import java.util.ArrayList;

import java.util.List;

import com.mongodb.AggregationOptions;

import com.mongodb.BasicDBObject;

import com.mongodb.Cursor;

import com.mongodb.DBCollection;

import com.mongodb.DBObject;

public class MongoSum {

public static void main(String[] args) {
DBCollection collection;
try {
// 获取连接
collection = MongoUtil.getCollection();
// 查询数据

List<DBObject> ops = new ArrayList<DBObject>();

String[] str = new String[2];
str[0]="$price";
str[1]="$quantity";

DBObject all = new BasicDBObject("_id",new BasicDBObject("month",new BasicDBObject("$month","$date")).append("day", new BasicDBObject("$dayOfMonth","$date")).append("year", new BasicDBObject("$year","$date")))
.append("totalPrice",new BasicDBObject("$sum",new BasicDBObject("$multiply",str)))
.append("averageQuantity", new BasicDBObject("$avg","$quantity"))
.append("count", new BasicDBObject("$sum",1));

DBObject count = new BasicDBObject("$group",all);

ops.add(count);

Cursor cursor = collection.aggregate(ops, AggregationOptions.builder().allowDiskUse(true).build());
while(cursor.hasNext()) {
DBObject doc = cursor.next();
System.out.println(doc);
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
}

}

工具类如下:

package test;

import java.net.UnknownHostException;

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.MongoClient;

import com.mongodb.ServerAddress;

/**

 * @author : suyuyuan

 * @date :2016年6月24日 上午10:36:28

 * @version 1.0

 */

public class MongoUtil {

private static String dbIp = "localhost";
private static int dbPort = 27017;
private static String mydb = "mongotest";
private static String table = "sales";

public static DBCollection getCollection() throws UnknownHostException {

// // 实例化Mongo对象,
// Mongo mongo = new Mongo(dbIp, dbPort);
// // 连接名为yourdb的数据库,假如数据库不存在的话,mongodb会自动建立
// DB db = mongo.getDB(dbUser);
// // 从Mongodb中获得名为myData的数据集合,如果该数据集合不存在,Mongodb会为其新建立
// DBCollection collection = db.getCollection(table);

MongoClient mongoClient = new MongoClient(new ServerAddress(dbIp, dbPort));
DB db = mongoClient.getDB(mydb);
DBCollection collection = db.getCollection(table);

return collection;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: