最近进行项目开发,公司用的原生mongo进行数据操作,找了很久找到了以下的原生操作方法
1.进行ip与port的封装,封装为ServerAddress对象
ServerAddress address = new ServerAddress(ip, port);
2.接下来封装用户名、数据库名、密码的对象
MongoCredential credential = MongoCredential.createMongoCRCredential(GlobalConfig.getValue("mongodbUserName"),
GlobalConfig.getValue("mongodb_1"), GlobalConfig.getValue("mongodbPwd").toCharArray());
3.建立mongo客户端的连接
MongoClient client = new MongoClient(address, Arrays.asList(credential));
DB mongoDb = client.getDB(GlobalConfig.getValue("mongodb_1"));
DBCollection doc = mongoDb.getCollection("User");
4.这里进新mong里面的条件封装,list添加的元素类似于mysql中的not in条件
List<String> list = new ArrayList<>();
list.add(null);
list.add("");
5.这个array数组封装查询条件
//相当于where条件
BasicDBObject[] array = {
new BasicDBObject("registerTime", new BasicDBObject("$gte",new Timestamp(calStart.getTimeInMillis()))),
new BasicDBObject("registerTime", new BasicDBObject("$lte",new Timestamp(calEnd.getTimeInMillis()))),
new BasicDBObject("recommendId", new BasicDBObject("$nin", list))
};
6.$and命令意思是指将array里面的条件进行与的连接相当于mysql的and
BasicDBObject cond = new BasicDBObject();
cond.put("$and", array);
7.$match指匹配其中的条件进行查询
DBObject match = new BasicDBObject("$match", cond);
8.想要查询得到的数据字段使用$project命令进行封装,数值标记为1
DBObject fields = new BasicDBObject("recommendName", 1);
DBObject project = new BasicDBObject("$project", fields);
9.这里引用$recommendName进行分组
DBObject _group = new BasicDBObject("recommendName", "$recommendName");
//相当于 group by recommendName,将分组后的数据封装为键值为_id的键值对
DBObject groupFields = new BasicDBObject("_id", _group);
10.进行计数求和,$sum命令进行求和,将求和结果定义为count
//相当于求出分组之下的和
groupFields.put("count", new BasicDBObject("$sum", 1));
//分组、排序、限制个数
11.$group命令表示进行分组查询
DBObject group = new BasicDBObject("$group", groupFields);
12.$limit命令进行个数限制
DBObject limit = new BasicDBObject("$limit", 10);
13.-1表示将结果按照count字段进行反序排列
DBObject sort = new BasicDBObject("$sort", new BasicDBObject("count", -1));
14.最后将整个命令进行封装,得到mongo输出对象output
AggregationOutput output = doc.aggregate(match,project,group,sort,limit);
15.接下来就是进行一些相关字段的获取封装为对象
int number = 1;
List<ETTopTen> nameList = new ArrayList<>();
for (DBObject obj : output.results()) {
Object obj2 = (Object) obj;
net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(obj2);
ETTopTen etTopTen = new ETTopTen();
etTopTen.setId(number++);
etTopTen.setNumber(Integer.parseInt(json.getString("count"))+1);
String userName = net.sf.json.JSONObject.fromObject(json.getString("_id")).getString("recommendName");
etTopTen.setUserName(userName);
nameList.add(etTopTen);
}
翻译为mysql命令就是:
select recommendName, count from (
select revommendName, count(revommendName) as count from db where recommendId not in("", null) group by recommendName limit 0, 10
)
不定期技术文章
更多技术文章,面试文章请扫描个人开发的小程序,码在下面哈~