1024programmer Mongodb Spring and MongoDB implement aggregation query

Spring and MongoDB implement aggregation query

Integrate MongoDB and Spring, find the corresponding version according to the development document.

According to official documents, we know that Spring must be version 3.0.x or above, and MongoDB must be version 1.6.5 or above.
If you want to integrate Spring and Mongodb, you must download the corresponding jar. There are mainly two jars used here, one is spring-data-document and spring-
There are two types of jars in data-commons, but the versions of the two types of jars must match to avoid jar conflicts, because the jar directory of the version behind commons has changed for all versions
This must be corresponding to the following is the jar download address

http://www.springsource.org/spring-data/mongodb

http://www.springsource.org/spring-data/commons

The following is the jar I downloaded and add the mongodb java driver package, spring
I won’t say more about jar addition
The Spring configuration file is as follows:

1.

2.
<beans xmlns="http://www.springframework.org/schema/beans" 

3.
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”

4.
xmlns:cOntext=”http://www.springframework.org/schema/context”

5.
xmlns:mOngo=”http://www.springframework.org/schema/data/mongo”

6.
xsi:schemaLocation=

7.
“http://www.springframework.org/schema/context

8.
     http://www.springframework.org/schema/context/spring-context-3.0.xsd 

9.
http://www.springframework.org/schema/data/mongo

10. http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd

11. http://www.springframework.org/schema/beans

12. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”> 

13.

14.  

15.

16.

17. <bean id="mongoTemplate" class=”org.springframework.data.document.mongodb.MongoTemplate”>

18.

19.

20.

21.

22. <bean id="personRepository" class=”com.mongo.repository.PersonRepository”> 

23.

24.

26.

27.
the

28.

29.
the

30.

31.

32.

33.

34.

35.

the

Define the interface for adding, deleting, checking and modifying:

public ininterface ModuleStatService
{

//Basic query

ModuleDaily
queryModuleDaily(Long moduleId, String date);

// aggregate query

ModuleDaily
genModuleDaily(GeneralHierarchy module, String startDate, String
endDate);

the

}

the

Implement the interface class:

@Service

public class ModuleStatServiceImpl implements ModuleStatService {

the

the

@Resource

private MongoTemplate
productMongo;

@Autowired

the
private MongoTemplate commonMongo;

the

@Override

public ModuleDaily
queryModuleDaily(Long moduleId, String date) {

return productMongo.findOne(Query.query(Criteria.where(“moduleId”).is(moduleId).and(“date”) .is(date)),

ModuleDaily.class,
Constant.COLLECTION_MODULE_DAILY);

}

the

public ModuleDaily
genModuleDaily(final GeneralHierarchy module, final String startDate, final String endDate) {

DBObject
result = commonMongo.execute(Constant.COLLECTION_URL_DAILY, new CollectionCallback() {

@Override

public DBObject doInCollection(DBCollection collection) throws MongoException, DataAccessException {

List patterns = new ArrayList();

for (String anchor : module. getAnchors()) {

patterns.add(Pattern.compile(anchor));

}

// Set the Where condition

BasicDBObject matchOpt = new BasicDBObject();

Map matchMap = new HashMap();

matchMap. put(“channel”,
module.getSiteName());//Set where condition channel=””

matchMap.put(“date”, (new BasicDBObject(“$gt”,
startDate)).append(“$lt”, endDate)); //Set where condition date>=startDate
and date<endDate

matchMap.put(“url”, new BasicDBObject(“$in”, patterns));
//Set this expression, patterns is an array of this expression, get url matching all regular data

matchOpt.put(“$match”, new BasicDBObject(matchMap));

the

the

// Count the number of rows for the grouping field and the grouping field defaults to return the result set

BasicDBObject groupOpt = new BasicDBObject();

Map groupMap = new HashMap();

groupMap.put(“_id”, “$date”);

groupMap.put(“totalPV”, new BasicDBObject(“$sum”,
“$pv”));

groupMap.put(“totalUV”, new BasicDBObject(“$sum”,
“$uv”));

groupMap.put(“totalDQ”, new BasicDBObject(“$sum”,
“$dq”));

groupMap.put(“totalRealUv”, new BasicDBObject(“$sum”,
“$realUv”));

groupOpt.put(“$group”, new BasicDBObject(groupMap));

the

AggregationOutput aggrResult = collection.aggregate(matchOpt,
groupOpt);

Iterator iter =
aggrResult.results().iterator();

DBObject result = null;

while (iter. hasNext()) {

result =
iter. next();

break;

}

return result;

}

});

the

//Extract the result set data and process it to the target object


ModuleDaily moduleDaily = new ModuleDaily();


moduleDaily.setModuleId(module.getId());


moduleDaily.setParentId(module.getParentId());


moduleDaily.setModuleName(module.getName());

if (result != null) {

moduleDaily.setPv((Long) result.get(“totalPV”));

moduleDaily.setUv((Long) result.get(“totalUV”));

moduleDaily.setDq((Long) result.get(“totalDQ”));

moduleDaily.setRealUv((Long) result.get(“totalRealUv”));

} else {

moduleDaily.setPv(0L);

moduleDaily.setUv(0L);

moduleDaily.setDq(0L);

moduleDaily.setRealUv((0L));

}

return moduleDaily;

}

 

}

the

the
The above implementation class lists the basic query and aggregation query. In the aggregation query, the grouping field is the result set field by default. Sometimes the grouping field is not necessarily an aggregation field, so it needs to be processed by the DB class. Examples are as follows:

the

private static void test(DBCollection dBCollection) {

try {

DB db = dBCollection. getDB();

// Set the Where condition

DBObject match = new BasicDBObject(“$match”, new BasicDBObject(“date”, (new BasicDBObject(“$gt”,

“2012-11-28”)).append(“$lt”, “2012-11-29”)));

// set group field

BasicDBObject groupFilters = new BasicDBObject(“_id”,
“$PRIORITY”);

// Count the number of rows for the grouping field

groupFilters. put(“count”, new BasicDBObject(“$sum”, 1));

BasicDBObject group = new BasicDBObject(“$group”,
groupFilters);

// Set the displayed field collection

DBObject fields = new BasicDBObject(“PRIORITY”, 1);

fields. put(“_id”, “$PRIORITY”);

DBObject project = new BasicDBObject(“$project”,
fields);

// get the result set

AggregationOutput output =
db.getCollection(“messages”).aggregate(match, project, group);

System.out.println(output.getCommandResult());

} catch (Exception e) {

e.printStackTrace();

}

}

the

In short, after integrating MongoDB through Spring, it is easy to add, delete, check and modify mongodb through MongoTemplate, especially using regular expression queries, which can effectively aggregate data according to business needs.

leName(module. getName());

if (result != null) {

moduleDaily.setPv((Long) result.get(“totalPV”));

moduleDaily.setUv((Long) result.get(“totalUV”));

moduleDaily.setDq((Long) result.get(“totalDQ”));

moduleDaily.setRealUv((Long) result.get(“totalRealUv”));

} else {

moduleDaily.setPv(0L);

moduleDaily.setUv(0L);

moduleDaily.setDq(0L);

moduleDaily.setRealUv((0L));

}

return moduleDaily;

}

 

}

the

the
The above implementation class lists the basic query and aggregation query. In the aggregation query, the grouping field is the result set field by default. Sometimes the grouping field is not necessarily an aggregation field, so it needs to be processed by the DB class. Examples are as follows:

the

private static void test(DBCollection dBCollection) {

try {

DB db = dBCollection. getDB();

// Set the Where condition

DBObject match = new BasicDBObject(“$match”, new BasicDBObject(“date”, (new BasicDBObject(“$gt”,

“2012-11-28”)).append(“$lt”, “2012-11-29”)));

// set group field

BasicDBObject groupFilters = new BasicDBObject(“_id”,
“$PRIORITY”);

// Count the number of rows for the grouping field

groupFilters. put(“count”, new BasicDBObject(“$sum”, 1));

BasicDBObject group = new BasicDBObject(“$group”,
groupFilters);

// Set the displayed field collection

DBObject fields = new BasicDBObject(“PRIORITY”, 1);

fields. put(“_id”, “$PRIORITY”);

DBObject project = new BasicDBObject(“$project”,
fields);

// get the result set

AggregationOutput output =
db.getCollection(“messages”).aggregate(match, project, group);

System.out.println(output.getCommandResult());

} catch (Exception e) {

e.printStackTrace();

}

}

the

In short, after integrating MongoDB through Spring, it is easy to add, delete, check and modify mongodb through MongoTemplate, especially using regular expression queries, which can effectively aggregate data according to business needs.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/spring-and-mongodb-implement-aggregation-query/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索