mongodb - 如何在 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"}
解决方案
您需要额外的$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
}
}
]);
推荐阅读
- reactjs - 反应本机中的redux auth状态问题
- scala - Scala将Map序列减少为每个键都有最大值的Map
- haskell - Functor / Applicative 可以绑定到一种特定的类型或结构吗?
- javascript - 如何使用 javascript 将内容从页面上的其他位置移动到选项卡中?
- windows-terminal - 如何打开带有 4 个窗格的 Windows 终端?
- typescript - 制作自定义 SaveButton 时,如何在 handleSubmitWithRedirect 上正确输入?
- javascript - Hook 的 useState 初始值在被记忆的回调中永远不会改变
- amazon-web-services - 从 ReactJS APP 检索 AWS App Config 配置
- c++ - 连续迭代器上的 SIMD 指令
- amazon-web-services - Gitlab CI失败找不到aws命令