gpt4 book ai didi

mongodb - 限制在组中推送返回的项目

转载 作者:可可西里 更新时间:2023-11-01 09:30:17 25 4
gpt4 key购买 nike

我需要按发件人分组 (fleche) 并从每个发件人处获取最后一条消息。我使用 $push$group 成功实现了这个想法,但它返回每个“fleche”(发件人)的所有消息。与消息日期相同的 pb,最后一个元素应该是 enought 。在 mongo 2.6.6 with aggregation framework 上有可能吗?
预期结果,我的实际查询的实际结果,实际查询和消息收集示例附在下面:
预期结果:

"result" : [ 
{
"_id" : 1,
"date" : [
1421948851800
],
"mess" : [
"dernier mess ffsdfsdfsd 2"
]
},
{
"_id" : 3,
"date" : [
1421948859593
],
"mess" : [
"dernier mess ffsdfsdfsd 2"

]
}

实际查询的实际结果:

"result" : [ 
{
"_id" : 1,
"date" : [
1421948851800,
1421947200606,
1421947163929,
1421947153646,
1421946853567
],
"mess" : [
"dernier mess ffsdfsdfsd 2",
"fssdfencore didon ! fds 2",
"fsd fds fds 2",
"safdsfdsfs sdf fie2",
"salut la companie"
]
},
{
"_id" : 3,
"date" : [
1421948859593,
1421947176679,
1421947098168
],
"mess" : [
"dernier mess ffsdfsdfsd 2",
"fssdfsdffsd ss fds 2",
"salut la companie"
]
}

实际查询:

db.messages.aggregate([

{$match :{cible :2 , lu:0} } ,
{ $sort : { date : -1 } },
{ $group : {_id : "$fleche", date : { $push : "$date" } , mess :{$push: "$mess" } } } ,
{$limit:20}

])

消息收集示例:

{
"_id" : ObjectId("54c12fe5a48da55ee08c7804"),
"fleche" : 1,
"cible" : 2,
"date" : 1421946853567,
"mess" : "salut la companie",
"lu" : 0
}
{
"_id" : ObjectId("54c130daa48da55ee08c7805"),
"fleche" : 3,
"cible" : 2,
"date" : 1421947098168,
"mess" : "salut la companie",
"lu" : 0
}
{
"_id" : ObjectId("54c13111a48da55ee08c7807"),
"fleche" : 1,
"cible" : 2,
"date" : 1421947153646,
"mess" : "safdsfdsfs sdf fie2",
"lu" : 0
}
{
"_id" : ObjectId("54c1311ba48da55ee08c7808"),
"fleche" : 1,
"cible" : 2,
"date" : 1421947163929,
"mess" : "fsd fds fds 2",
"lu" : 0
}
{
"_id" : ObjectId("54c13128a48da55ee08c7809"),
"fleche" : 3,
"cible" : 2,
"date" : 1421947176679,
"mess" : "fssdfsdffsd ss fds 2",
"lu" : 0
}

最佳答案

您可以使用 $first$last

db.messages.aggregate([

{$match :{cible :2 , lu:0} } ,
{ $sort : { date : -1 } },
{ $group : {_id : "$fleche", date : { $first : "$date" } , mess :{$first: "$mess" } } } ,
{$limit:20}

])

输出将是:

{
"result" : [
{
"_id" : 1,
"date" : 1421947163929,
"mess" : "fsd fds fds 2"
},
{
"_id" : 3,
"date" : 1421947176679,
"mess" : "fssdfsdffsd ss fds 2"
}
],
"ok" : 1
}

关于mongodb - 限制在组中推送返回的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28096340/

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