【发布时间】:2019-07-05 15:28:30
【问题描述】:
我有一个聚合查询,我在其中加入了 3 个集合。我想根据其中两个集合中的字段过滤搜索。问题是,我只能在 mongoose 初始化的初始集合上使用 $match。
这是查询:
var pipeline = [
{
$lookup: {
from: 'blurts',
localField: 'followee',
foreignField: 'author.id',
as: 'followerBlurts'
}
},
{
$unwind: '$followerBlurts'
},
{
$lookup: {
from: 'users',
localField: 'followee',
foreignField: '_id',
as: 'usertbl'
}
},
{
$unwind: '$usertbl'
},
{
$match: {
'follower': { $eq: req.user._id },
//'blurtDate': { $gte: qryDateFrom, $lte: qryDateTo }
}
},
{
$sample: { 'size': 42 }
},
{
$project: {
_id: '$followerBlurts._id',
name: '$usertbl.name',
smImg: '$usertbl.smImg',
text: '$followerBlurts.text',
vote: '$followerBlurts.vote',
blurtDate: '$followerBlurts.blurtDate',
blurtImg: '$followerBlurts.blurtImg'
}
}
];
keystone.list('Follow').model.aggregate(pipeline)
.sort({blurtDate: -1})
.cursor().exec()
.toArray(function(err, data) {
if (!err) {
res.json(data);
} else {
console.log('Error getting following blurts --> ' + err);
}
});
在管道中,我只能在“关注”模型上使用 $match。当我在“Blurt”模型上使用 $match 时,它只是忽略了条件(您可以看到我试图将它包含在 $match 下的注释行中的位置)。
令人困惑的是,我可以在 .sort 方法中使用该字段,但不能在 $match 条件中使用。
非常感谢任何帮助。
【问题讨论】:
-
你试过
followerBlurts.blurtDate -
@Bajal 哇,这确实有效。我尝试使用 $ 前缀 ($followerBlurts) 并得到一个明显的错误,并且认为没有前缀我无法引用它。我觉得这很奇怪,但到目前为止它似乎确实有效。谢谢。如果您愿意,可以发布答案,我将标记为解决方案。编辑:我现在看到我使用的是“unwind”引用而不是“as”引用。
标签: mongodb mongoose mongodb-query aggregation-framework