当前位置:网站首页>Mongodb group one piece of data in each group
Mongodb group one piece of data in each group
2022-07-23 17:46:00 【pilaf1990】
Demand background
There is one mongo collection, The driver has information about where the goods are stored , The main fields are
_id: mongodb Default primary key field
orderId: Order id
positionTime: The timestamp of the time on the position
lon: Longitude information
lat: Latitude information
Now we need to support according to a batch of orders id, Check the longitude and latitude of their latest position .
Demand analysis
According to the demand background , You can know , The query condition is based on the order id As a group , In each group, according to positionTime null , Then return all fields of the first record in the group .
stay NoSQL Booster Query statements in :
// _id Overridden query method
db.position_collection
.aggregate([
{
// Filter out qualified records , Order here id list
$match: { orderId: {$in: [26556031845626880,26550496434145792]}}},
// According to the order id Ascending , Sort the positioning time in descending order
{$sort: { orderId: 1, positionTime:-1}},
{$group:{
// according to orderId Field grouping ,mongodb Requirements must be used _id To represent the grouped fields , But the result of this query document Medium _id The field becomes orderId 了
_id:"$orderId",
// If you want to put the of the watch itself _id Field returns how to do ? You can add a line _id:{$first: "$_id"} Well ? The answer is no ,mongodb Will report a mistake
// Returns the of the first record in the group orderId
orderId:{$first: "$orderId"},
// Returns the of the first record in the group positionTime
positionTime:{$first: "$positionTime"}
}
}
])
// limit The order quantity should be used as a limit later
.limit(10)
// _id Query method that will not be overwritten
db.position_collection
.aggregate([
{$match: { orderId: {$in: [26556031845626880,26550496434145792]}}},
{$sort: { orderId: 1, positionTime:-1}},
{$group:{
_id:"$orderId",
// adopt $$ROOT Get the original recorded information , Deposit in doc in
doc:{$first: "$$ROOT"},
}},
// from doc Restore the original recorded information , Including the most primitive _id
{$replaceRoot: { newRoot: "$doc" }}
])
.limit(10)
Java Demo Code
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.model.Accumulators;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import org.bson.BsonDocument;
import org.bson.BsonDocumentWriter;
import org.bson.Document;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class MongoDemo {
private void queryLatestPosition(String collectionName,List<Long> orderIds) {
// because group The back needs to be based on orderId grouping , Take the record with the largest positioning time ,group Later, it is required to use _id To represent grouped fields , But there's a problem ,
// mongodb Found out document From the Central Plains _id The field will be set to a document, If you want to put the original _id Fields are also taken out , To use replaceRoot
// But our company mongo maven Used in dependency mongo-java-driver-3.2.2 Version of Aggregates There is no replaceRoot Method available , So he
// imitation Aggregates.group Method to create one by yourself .
// About replaceRoot Problem solved , You can refer to https://stackoverflow.com/questions/52566913/how-to-group-in-mongodb-and-return-all-fields-in-result/52578475
BsonDocumentWriter bsonDocumentWriter = new BsonDocumentWriter(new BsonDocument());
bsonDocumentWriter.writeStartDocument();
bsonDocumentWriter.writeStartDocument("$replaceRoot");
bsonDocumentWriter.writeString("newRoot","$doc");
bsonDocumentWriter.writeEndDocument();
bsonDocumentWriter.writeEndDocument();
BsonDocument replaceRoot = bsonDocumentWriter.getDocument();
AggregateIterable<Document> aggregateIterable = myMongoClient.getCollection(collectionName)
.aggregate(Arrays.asList(
// according to orderId List filter records
Aggregates.match(Filters.in("orderId",orderIds)),
// according to orderId Ascending 、positionTime Descending Sort
Aggregates.sort(new Document().append("orderId",1).append("positionTime",-1)),
// according to orderId grouping
Aggregates.group(
new Document("_id", "$orderId"),
Arrays.asList(
// Take the first data of the group , namely positionTime The biggest one , Put it in doc In the field , For follow-up replaceRoot Replacement
Accumulators.first("doc","$$ROOT"))
),
// If your API There is Aggregates.replaceRoot, Just use it directly
replaceRoot,
Aggregates.limit(orderIds.size())
))
// Set timeout
.maxTime(4000, TimeUnit.MILLISECONDS);
for (Document document : aggregateIterable) {
// Traverse document To deal with
}
}
}
Reference material :
1.https://stackoverflow.com/questions/52566913/how-to-group-in-mongodb-and-return-all-fields-in-result/52578475
边栏推荐
- Rust中的dyn关键字
- Record the range of data that MySQL update will lock
- 单细胞文献学习(part6)--ForestFireClustering for sc sequencing combines iterative label propagation with ...
- Solutions to sap Hana database backup failure
- Debug:形参带有Const修饰符号需要注意的地方
- 你真的了解Redis的持久化机制吗?
- Do you really understand the persistence mechanism of redis?
- SAP HANA数据库备份失败解决办法
- 李宏毅《机器学习》丨7. Conclusion(总结)
- Create a flow using flow builder in kotlin
猜你喜欢

USB Type-C PD CC逻辑芯片中的角色定义

Software configuration | Anaconda download, installation, environment configuration and uninstall

rust求数组中最大值

New opportunities for cultural tourism in the era of digital intelligence? China Mobile Migu creates "the first island in the yuan universe"

Leetcode question brushing record
![[introduction series of redis] redis builds master-slave servers](/img/94/505ec8eeb9a10e09a00f61565cbaba.png)
[introduction series of redis] redis builds master-slave servers
一加OnePlus 10T的一系列规格在产品发布前被披露

Food safety | what is the origin of plant meat that sounds very healthy?

Kubernetes kubelet hard core knowledge architecture

Aike AI frontier promotion (7.23)
随机推荐
The use method of quota command is expanded in detail, and the carrying method of quota command in RHEL 7! Disk capacity quota!
JS tool CECP
LeetCode_724_寻找数组的中心下标
Do you really understand the persistence mechanism of redis?
keyup.native在el-input中的使用
leetcode刷题:动态规划04(不同路径)
网页基础模版
Date formatting
Analyze optimism replay contract address attack events
USB Type-C PD CC逻辑芯片中的角色定义
sublime text使用技巧
Unity production QR code scanning
Food safety | eight things you must know when choosing probiotic products
rust统计文件中单词出现的次数
Tapdata 与优炫数据库完成产品兼容性互认证
元素内容必须由格式正确的字符数据或标记组成
Why do you get confused when you ask JVM???
爱可可AI前沿推介(7.23)
Food safety | drinking fresh milk may infect tuberculosis? Take you to know what is milk sterilization
Tampermonkey究竟有什么用?