如何使用聚合为集合中的所有记录删除特定值:
具有数据收集:
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
present_working:true,
age: 55,
location: "texas",
date:2019-11-25T10:49:36.534+00:00
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
present_working:true,
location: "texas",
date:null
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
location: "texas",
date:null
}
]
删除记录中有date:null
的行。无需在数据库中删除数据,而应仅在聚合管道中对其进行修改
仅删除date:null
后的预期输出:
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
present_working:true,
age: 55,
location: "texas",
date:2019-11-25T10:49:36.534+00:00
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
present_working:true,
location: "texas"
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
location: "texas"
}
]
MongoDB版本: 4.0
答案 0 :(得分:1)
您可以使用$ifNull运算符和$$REMOVE
来做到这一点:
db.collection.aggregate([
{
$addFields: {
date: {
$ifNull: [
"$date",
"$$REMOVE"
]
}
}
}
])