首页 > 解决方案 > 如何在 mongoDB 中排除 $project 计算字段

问题描述

我在聚合项目中创建了一个新字段进行比较,我不希望该字段显示在最终结果中。我怎样才能排除它?这是我的示例查询。在这种情况下,我想隐藏该字段yearDate。可能吗?

db.user.aggregate([
    $project: {name: 1, yearDate: {$month: '$date'}, content: 1, date: 1}},
    {
        $match: {
            $and: [
                {
                    yearDate: {$ne: 2018}
                },
                {
                    content: /2018/
                }
            ]
        }
    },
    {
        $sort: {
            date: 1
        }
    }
]);

当前结果

{ "date" : "2018-11-01 02:42:20", "content" : 'abc2018', "yearDate" : "2018", "name": "test"}

预期结果

{ "date" : "2018-11-01 02:42:20", "content" : 'abc2018',"name": "test"}

标签: mongodb

解决方案


您需要额外的$project阶段才能将该字段从最终结果中排除,请尝试:

db.user.aggregate([
    $project: {name: 1, yearDate: {$month: '$date'}, content: 1, date: 1}},
    {
        $match: {
            $and: [
                {
                    yearDate: {$ne: 2018}
                },
                {
                    content: /2018/
                }
            ]
        }
    },
    {
        $sort: {
            date: 1
        }
    },
    {
        $project: {
            yearDate: 0
        }
    }
]);

推荐阅读