gpt4 book ai didi

java - Mongodb 聚合(Java/Spring)查询以获取最后一个子元素

转载 作者:行者123 更新时间:2023-11-30 02:44:01 25 4
gpt4 key购买 nike

我有以下结构名称讨论。我想获取用户讨论中的最后一条消息。我尝试遵循不完整的 Spring MongoDB 查询,您能否让我知道如何在每个讨论中仅获取一条消息(按最后修改日期排序),或者查找用户是对话中最后一条消息的接收者的讨论。

Aggregation aggr = newAggregation(
match(Criteria.where("participants").regex(Pattern.compile(userid))),
unwind("messages"),
match(new Criteria().orOperator(Criteria.where("messages.touserId").is(userid),Criteria.where("messages.fromuserId").is(userid))),
sort(Direction.DESC, "messages.lastModifiedDate"),
group("_id").push("messages").as("messages"),
project("_id","messages")
);

{
"_id": {
"$oid": "57c2d7c8e4b0bcf181b7db0a"
},
"_class": "xxxxx",
"participants": [
"56893b22e4b0e8d1c6a25783",
"56893bb6e4b0e8d1c6a25785",
"577c2f6ee4b09ccb44d14415"
],
"messages": [
{
"_id": {
"$oid": "57c2d7c8e4b0bcf181b7db08"
},
"fromuserId": "577c2f6ee4b09ccb44d14415",
"fromuser": "xxxx",
"touserId": "56893b22e4b0e8d1c6a25783",
"touser": "Bloreshop1",
"message": "Check Product Price",
"isMute": false,
"index": 1,
"createDate": {
"$date": "2016-08-28T12:23:36.037Z"
},
"lastModifiedDate": {
"$date": "2016-08-28T12:23:36.037Z"
},
"createdBy": "xxxx",
"lastModifiedBy": "xxxxx"
},
{
"_id": {
"$oid": "57c2d7c8e4b0bcf181b7db09"
},
"fromuserId": "577c2f6ee4b09ccb44d14415",
"fromuser": "xxxxxx",
"touserId": "56893bb6e4b0e8d1c6a25785",
"touser": "Bloreshop2",
"message": "Check Product Price",
"isMute": false,
"index": 2,
"createDate": {
"$date": "2016-08-28T12:23:36.302Z"
},
"lastModifiedDate": {
"$date": "2016-08-28T12:23:36.302Z"
},
"createdBy": "xxxxx",
"lastModifiedBy": "xxx"
}
],
"discussionTopic": "Check Product Price",
"messageCount": 2,
"createDate": {
"$date": "2016-08-28T12:23:36.318Z"
},
"lastModifiedDate": {
"$date": "2016-08-28T12:23:36.318Z"
},
"createdBy": "xxxx",
"lastModifiedBy": "xxxxx"
}

最佳答案

您正在寻找$slice(aggregation) 。当前发布的1.9.5版本不支持切片。

Aggregation aggr = newAggregation(
match(Criteria.where("participants").regex(Pattern.compile(userid))),
unwind("messages"),
match(new Criteria().orOperator(Criteria.where("messages.touserId").is(userid), Criteria.where("messages.fromuserId").is(userid))),
sort(Direction.DESC, "messages.lastModifiedDate"),
group("_id").push("messages").as("messages"),
project("_id").and("messages").project("slice", 1));

未发布版本(2.x)支持切片

Aggregation aggr = newAggregation(
match(Criteria.where("participants").regex(Pattern.compile(userid))),
unwind("messages"),
match(new Criteria().orOperator(Criteria.where("messages.touserId").is(userid), Criteria.where("messages.fromuserId").is(userid))),
sort(Direction.DESC, "messages.lastModifiedDate"),
group("_id").push("messages").as("messages"),
project("_id").and("messages").slice(1));

关于java - Mongodb 聚合(Java/Spring)查询以获取最后一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40775170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com