我从一个集合中提取一组记录并加入另一个集合。
我想在投影字段中添加一个字段,但我收到错误 - 代码和错误如下:
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"
}
答案 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
}
}
]
);