1024programmer Mongodb MongoDB Advanced Aggregate Query Usage Guide

MongoDB Advanced Aggregate Query Usage Guide

MongoDB version is: 2.0.8

The system is: 64-bit Ubuntu 12.04

First show him my table structure [Oh sorry, Mongo is called a collection]

MongoDB Advanced Aggregate Query

As you can see, I try to simulate real life scenarios as much as possible. This is a Person entity, he has basic manId, manName,
There are friends [myFriends], there are favorite fruits [fruits], and each fruit has a favorite weight.

Unfortunately, you also saw a “_class” field? Because I am a Java developer, I also like to use Spring, so I chose Spring
Data Mongo’s class library [it can be regarded as a framework, but I don’t think so].

Now many people are tired of seeing Spring and are starting to get bored. Yes, Spring has great ambitions, and he almost wants to monopolize everything in Java. There is no way I can’t do without him since I used Spring, so that I basically don’t need to learn other frameworks. I have learned a lot about Spring, such as: Spring
Security/Spring Integration/Spring
Batch and so on. . . He who didn’t invent the wheel has already provided many scenarios in programming. I used those scenarios to solve many problems in my work and made my work very efficient. Thus I have time to learn more about it. Spring
Data Mongo encapsulates mongodb java
The driver provides MongoTemplate with the same programming style as SpringJDBC/Template.

See: http://static.springsource.org/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.html

Stop talking nonsense, let’s go straight to MongoDB.

When my colleagues and I were testing Mongo, the index was less than half written. He wanted to query the maximum value of a certain field, but after searching for documents for a long time, he couldn’t find a function about max. I am also wondering why this is a regular function and not provided?
Later, after reviewing the information, it was determined that Mongo does not provide direct max and min functions. But it is possible to achieve this in an indirect way [sort and limit].

To query the maximum value, we only need to arrange the result set in descending order and take the first value.

As in my example, I want to get the oldest person in the collection.

db.person.find({}).sort({“age” : -1}).limit(1)

On the contrary, if you want the youngest person, you only need to change the sort to {“age”: 1}.

Of course we use sort, which is fine for a small number of documents. When you need to index age for a large amount of data, otherwise this operation is time-consuming.

MongoDB’s destinct command is the easiest tool to get a list of distinct values ​​in a particular field. This command works for normal fields, array fields [myFriends] and array embedded documents [fruits].

Like the picture above, I think the fruits and myFriends fields are different. Many materials and examples on the Internet do not mention this scenario, because our business is a model like fruits, and I have tested it. It is also possible for fruits.fruitId.

As in the table structure above, I want to count all my favorite fruits.

db.person.distinct(“fruits.fruitId”)

He executed it successfully. output like:

[ “aaa”, “bbb”, “ccc”, “www”, “xxx”, “yyy”, “zzz”, “rrr” ]

I want to count how many people in the collection [by name]

db.person.distinct(“manName”)

I want to count the friends of the specified number of people who follow in common.

db.person.distinct(“myFriends”, {“manName” : {“$in” : [“ZhenQin”, “YangYan”]}})

output like:

[ “234567”, “345678”, “456789”, “987654”, “ni”, “wo” ]

So what if I use Java? I’m just demonstrating the Mongo command, how does it work with Spring Data Mongo?

Spring Schema:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:cOntext=”http://www.springframework.org/schema/context”
xmlns:mOngo=”http://www.springframework.org/schema/data/mongo”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd”>

 
<mongo:db-factory id="mongoDbFactory"
mongo-ref=”mongo”
dbname=”mongotest” />

Tests for max and min:

@Test
public void testMaxAndMinAge() throws Exception {
Query q = new BasicQuery(“{}”).with(new Sort(new Sort.Order(Sort.Direction.ASC, “age”))).limit(1);
Person result = mongoTemplate.findOne(q, Person.class);
log.info(result);
q = new BasicQuery(“{}”).with(new Sort(new Sort.Order(Sort.Direction.DESC, “age”))).limit(1);
result = mongoTemplate.findOne(q, Person.class);
log.info(result);
}

distincttest:

@Test
public void testDistinct() throws Exception {
List result = mongoTemplate.getCollection(“person”).distinct(“myFriends”);
for (Object o : result) {
    log.info(o);
}
log.info(“============================================== =======================”);
Query query = Query.query(Criteria.where(“manId”).is(“123456”));
  result = mongoTemplate.getCollection(“person”).distinct(“myFriends”, query.getQueryObject());
for (Object o : result) {
    log.info(o);
}
log.info(“============================================== =======================”);
  result = mongoTemplate.getCollection(“person”).distinct(“fruits.fruitId”);
for (Object o : result) {
    log.info(o);
}
}

The output result is:

12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ================================== ======================================
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ================================== ======================================
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
12-22 14:13:45 [INFO] [support.GenericApplicationContext(1020)] Closing org.springframework.context.support.GenericApplicationContext@1e0a91ff: startup date [Sat Dec 22 14:13:44 CST 2012]; root of context hierarchy
Here I want to make a special note, when Spring Data Mongo is used, such as findOne(query,
Person.class) it will convert the result set of the query into an object of the Person class. Spring Data
This is the case in many APIs of Mongo, where a Bean class object is passed in. Because the distinct test outputs a list, I use the mongo-java-driver API. They are all very simple. The only thing is Query, an object provided by Spring. I hope readers will notice that it encapsulates almost all conditional queries, sort, limit and other information.

FO] [t.MongoAdvaceQueryTest(85)] ccc
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
12-22 14:13:45 [INFO] [support.GenericApplicationContext(1020)] Closing org.springframework.context.support.GenericApplicationContext@1e0a91ff: startup date [Sat Dec 22 14:13:44 CST 2012]; root of context hierarchy
Here I want to make a special note, when Spring Data Mongo is used, such as findOne(query,
Person.class) it will convert the result set of the query into an object of the Person class. Spring Data
This is the case in many APIs of Mongo, where a Bean class object is passed in. Because the distinct test outputs a list, I use the mongo-java-driver API. They are all very simple. The only thing is Query, an object provided by Spring. I hope readers will notice that it encapsulates almost all conditional queries, sort, limit and other information.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/mongodb-advanced-aggregate-query-usage-guide/

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
首页
微信
电话
搜索