这是我的数据结构
{
"_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([
{
"$lookup" : {
"from" : "issues",
"localField" : "issues.str",
"foreignField" : "_id.str",
"as" : "issues"
}
},
{$sort: {weight: -1, "issues.lastUpdatedTime": 1}}
{
$group:
{
_id: "$issues",
},
},
])
我得到的结果如下。
但我不需要上面结果中显示的外部_id字段。请帮我解决这个问题。
答案 0 :(得分:1)
首先$展开问题子数组并使用其结果可以应用排序,跳过和限制
答案 1 :(得分:0)
您的sort
不适用于字段issues.lastUpdatedTime
,因为issues
是$lookup
之后的对象数组,而不是普通对象。所以你需要先$unwind
然后申请sort
在sort
之后,您应该使用skip
和limit
。像
{$unwind:"$issues"},
{$sort: {weight: -1, "issues.lastUpdatedTime": 1}},
{ $skip: 10 },// set value as you need
{ $limit : 50 }// set value as you need
注意:$limit
始终应该在$skip
之后aggregation
。所以代码就像
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}
]);
注意:如果您想在分组后返回固定数量的文档,那么您应该使用$skip
和$limit
anfter $group
阶段