我有一个非常简单的使用$ lookup和$ match的MongoDb查询。我的问题是我无法确定查询中$ match的正确位置。如果我将$ match放在$ lookup之上,我会得到预期的(通过$ match正确过滤)结果,但它们不包含链接文档的“world”数组。如果我将$ match放在查询下方,我会获得所有父记录,包括链接文档的“world”数组,但$ match不起作用。
我做错了什么?...
server.get(`${routePfx}/${model}s/with-linked`, function (req, res, next) {
console && console.log('Finding all with linked names ' + model.toUpperCase() + 's...');
db.collection(model).aggregate(
{
"$lookup": {
from: "world",
localField: "worldId",
foreignField: "_id",
as: "world"
}
},
{ "$match": { "del": false } }
).toArray(function (err, docs) {
res.json(201, docs);
next();
});
});
编辑:我发现了它!你注意到了这个微小的差异吗?...
server.get(`${routePfx}/${model}/:id/with-linked`, function (req, res, next) {
console && console.log('Finding ' + model.toUpperCase() + ' by Id with linked names...');
db.collection(model).aggregate([
{ "$match": { "_id": new ObjectId(req.params.id) } },
{
"$lookup": {
from: "world",
localField: "worldId",
foreignField: "_id",
as: "world"
}
}
]).toArray(function (err, docs) {
res.json(201, docs);
next();
});
});
答案 0 :(得分:0)
聚合函数需要一个数组......
server.get(`${routePfx}/${model}/:id/with-linked`, function (req, res, next) {
console && console.log('Finding ' + model.toUpperCase() + ' by Id with linked names...');
db.collection(model).aggregate([
{ "$match": { "_id": new ObjectId(req.params.id) } },
{
"$lookup": {
from: "world",
localField: "worldId",
foreignField: "_id",
as: "world"
}
}
]).toArray(function (err, docs) {
res.json(201, docs);
next();
});
});