$ arrayElemAt的第一个参数必须是一个数组

时间:2018-06-01 14:49:52

标签: mongodb mongodb-query aggregation-framework

我从一个集合中提取一组记录并加入另一个集合。

我想在投影字段中添加一个字段,但我收到错误 - 代码和错误如下:

db.getCollection("ConnectionEntity").aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $match: {
                "Id":"9c06cb0c-966a-4f6b-b087-816587629079"
            }
        },

        // Stage 2
        {
            $lookup: // Equality Match
            {
                from: "Enterprise",
                localField: "EnterpriseId",
                foreignField: "_id",
                as: "joined"
            }
        },

        // Stage 3
        {
            $project: {                 
                "Enterprise": {"$arrayElemAt": ["$joined.Profile", 0]}
            }
        },

        // Stage 4 - doesn't work
        {
            $addFields: {
                "Enterprise.Id": {"$arrayElemAt": ["$joined._id", 0]}
            }
        },
    ]
);

错误:

The following error occurred while attempting to execute the aggregate query

Mongo Server error (MongoCommandException): Command failed with error 28689: '$arrayElemAt's first argument must be an array'.

The full response is:
{ 

    "_t" : "OKMongoResponse", 

    "ok" : NumberInt(0), 

    "code" : NumberInt(28689), 

    "errmsg" : "$arrayElemAt's first argument must be an array", 

    "$err" : "$arrayElemAt's first argument must be an array"

}

1 个答案:

答案 0 :(得分:2)

在您的代码中Stage 4正在尝试引用joined中放弃的Stage 3数组(您只隐式地投射Enterprise字段和_id) 。有很多方法可以解决这个问题,例如,您可以使用$addFields中的Stage 4来保留joined数组并稍后删除它:

db.ConnectionEntity.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $match: {
                "Id":"9c06cb0c-966a-4f6b-b087-816587629079"
            }
        },

        // Stage 2
        {
            $lookup: // Equality Match
            {
                from: "Enterprise",
                localField: "EnterpriseId",
                foreignField: "_id",
                as: "joined"
            }
        },

        // Stage 3
        {
            $addFields: {                 
                "Enterprise": {"$arrayElemAt": ["$joined.Profile", 0]}
            }
        },

        // Stage 4
        {
            $addFields: {
                "Enterprise.Id": {"$arrayElemAt": ["$joined._id", 0]}
            }
        },

        //get rid of joined if it's no longer useful
        {
           $project: {
               joined: 0
           }
        }
    ]
);