mongoDB $match聚合在没有查询时返回空数组

问题描述 投票:0回答:1

我在聚合管道中使用 $match 。当我没有在 $match 中传递查询时,它会打印空数组。但我想要 $match 中存在空查询时的所有数据。同时如果查询不匹配,那么它应该打印空数组。如何做到这一点?.

export const getMovies = async (req, res) => {
const actorname = req.query.name
const genrename = req.query.genre
const movies = await Movie.aggregate(
    [
        { $addFields: { genre: '$genres' } },
        { $match: { name: actorname } },
        { $unwind: "$genre" },
        {
            $group: {
                _id: '$genre',
                movieCount: { $sum: 1 },
                movies: {
                    $push:
                    {
                        movie: "$movie",
                        genre: "$genres",
                        name: "$name",
                        rating: "$rating"
                    }
                }
            }
        },
        { $addFields: { genre: '$_id' } },
        { $project: { _id: 0 } },
        { $match: { genre: genrename } }
    ]
)
res.status(200).json({ movies })}
node.js mongodb express aggregation-framework aggregation
1个回答
0
投票

这不应该发生,您能否分享执行聚合的代码。如果您检查附加的图像,一个空的 $match 阶段只会与任何内容匹配,或者没有查询。就像做一个空的查找操作,它会返回所有内容。

© www.soinside.com 2019 - 2024. All rights reserved.