过滤数组并返回特定属性

时间:2016-06-01 12:33:30

标签: mongodb mongodb-query aggregation-framework

我有以下投射:

db.tickets.aggregate([
{
  $match: {
    "satisfaction_rating.id": {"$exists": true}
  }
},
{
  $project: {
    "ticketId": "$id",
    "employee": "$assignee.name",
    "subject": "$subject",
    "memberId": {
      "$filter": {
         "input": "$custom_fields",
         "as": "field",
         "cond": {"$eq": ["$$field.id", 24685851]}
       }
    },
    "requester": "$requester.name",
    "created": "$created_at",
    "solved": "$metric_set.solved_at",
    "resolutionTimeInHours": {"$trunc": {"$divide": ["$metric_set.full_resolution_time_in_minutes.business", 60]}},
    "score": "$satisfaction_rating.score",
    "comment": "$satisfaction_rating.comment"
  }
},
{
  $out: "satisfaction"
}]);

$ filter返回一个数组。我想要做的是获取第一个元素并获取一个属性,该属性应该绑定到memberId而不是带有一个元素的数组。

我环顾四周但没有找到合适的解决方案。 谁能给我一个提示?

2 个答案:

答案 0 :(得分:4)

@ user3100115让我走向正确的方向。

这是我的最终解决方案:

"memberId": {
  "$let": {
      "vars": {
             "memberId": {
                "$arrayElemAt": [
                {"$filter": {
                        "input": "$custom_fields",
                        "as": "field",
                        "cond": {"$eq": ["$$field.id", 24685851]}
                }}
                ,0]
                }   
        },
        "in": "$$memberId.value"
    }
}

答案 1 :(得分:2)

您可以使用a similar question regarding python运算符从$arrayElemAt的结果中返回元素,并使用$filter运算符和$let来访问子文档字段。

"memberId": {
    "$let": {
        "vars": { 
            "field": { 
                "$arrayElemAt": [
                    "$filter": {
                        "input": "$custom_fields",
                        "as": "field",
                        "cond": { "$eq": [ "$$field.id", 24685851 ]}
                    },
                    0
                ]
            }
        },
        "in": "$$field.id"
    }
}