【问题标题】:Use $match on fields from two separate collections in an aggregate query mongodb在聚合查询 mongodb 中对来自两个单独集合的字段使用 $match
【发布时间】: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


【解决方案1】:

您可以使用 mongo dot notation 访问正在通过 $lookup 查找的集合的元素。

https://docs.mongodb.com/manual/core/document/#dot-notation

因此,在这种情况下,followerBlurts.blurtDate 应该为您提供您正在寻找的价值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-13
    • 2023-03-28
    • 2021-12-16
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    • 2020-04-25
    相关资源
    最近更新 更多