gpt4 book ai didi

node.js - 下图聚合查询中如何添加sort,limit,skip?

转载 作者:搜寻专家 更新时间:2023-10-30 23:32:33 25 4
gpt4 key购买 nike

这是我的数据结构

{
"_id" : ObjectId("57f37f18517f72bc09ee7632"),
"name" : "testdata",
"createdBy" : "57f1fdef1d3c40141617d215",

"transitionEnabled" : false,
"status" : "active",
"createdDateTime" : ISODate("2016-10-04T10:06:16.195Z"),
"accounts" : [
"57f37f75517f72bc09ee7634"
],
"deliverables" : [],
"risks" : [],
"issues" : {
"_id" : ObjectId("57f38398517f72bc09ee7680"),
"title" : "test",
"description" : "Delay in testing due to issues with Provider Finder dataload in the test region. This has impacted the production release planned for Sep 30th",
"plannedStartDate" : ISODate("2016-09-01T00:00:00.000Z"),
"plannedEndDate" : ISODate("2016-10-30T00:00:00.000Z"),
"assignedTo" : "57f375ea517f72bc09ee762a",
"createdBy" : ObjectId("57f375ea517f72bc09ee762a"),
"likes" : 0,
"createdDateTime" : ISODate("2016-10-04T10:25:28.301Z"),
"status" : "open",
"stakeholders" : [],
"__v" : 0,
"lastUpdatedTime" : ISODate("2019-11-15T09:19:06.279Z")
},
"__v" : 0
}

我想按组织选择所有问题组,我想对这些数据实现排序、限制和跳过(子数组仅从上面发布数据)。为此,我尝试了以下代码

db.organizations.aggregate([
{
“$查找”:{
“来自”:“问题”,
“localField”:“issues.str”,
“foreignField”:“_id.str”,
“作为”:“问题”
}
},
{$sort: {weight: -1, "issues.lastUpdatedTime": 1}}
{
$组:
{
_id: "$问题",
},
},
])

我得到的结果如下。

enter image description here如何对以下查询进行排序和设置限制并跳过?查询返回的结果也已附上。

但我不需要上面结果中显示的外部 _id 字段。请帮我解决这个问题。

最佳答案

您的 sort 不适用于字段 issues.lastUpdatedTime 因为 issues$lookup 之后的对象数组只是不是一个普通的对象。所以你需要先 $unwind 然后应用 sortsort 之后,您应该使用 skiplimit。喜欢

{$unwind:"$issues"},
{$sort: {weight: -1, "issues.lastUpdatedTime": 1}},
{ $skip: 10 },// set value as you need
{ $limit : 50 }// set value as you need

注意:对于聚合$limit 始终应该在$skip 之后。所以代码会像

db.organizations.aggregate([
{
"$lookup": { "from": "issues", "localField": "issues.str", "foreignField": "_id.str", "as": "issues" }
},
{$unwind:"$issues"},
{$sort: {weight: -1, "issues.lastUpdatedTime": 1}},
{$skip: 10},
{$limit: 50}
]);

注意:如果你想在分组后返回固定数量的文档,那么你应该在 $group 阶段之后使用 $skip$limit

关于node.js - 下图聚合查询中如何添加sort,limit,skip?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47385968/

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