在 MongoDB 版本上 >= 3.2:
您可以利用.bulkWrite():
let bulkArr = [
{
updateMany: {
filter: { name: null },
update: { $unset: { name: 1 } }
}
},
{
updateMany: {
filter: { Roll_no: null },
update: { $unset: { Roll_no: 1 } }
}
},
{
updateMany: {
filter: { hobby: null },
update: { $unset: { hobby: 1 } }
}
},
];
/** All filter conditions will be executed on all docs
* but respective update operation will only be executed if respective filter matches (kind of individual ops) */
db.collection.bulkWrite(bulkArr);
参考: bulkwrite
在 MongoDB 版本上 >= 4.2:
由于您想删除具有null 值的多个字段(其中字段名称无法列出或未知),请尝试以下查询:
db.collection.update(
{}, // Try to use a filter if possible
[
/**
* using project as first stage in aggregation-pipeline
* Iterate on keys/fields of document & remove fields where their value is 'null'
*/
{
$project: {
doc: {
$arrayToObject: { $filter: { input: { $objectToArray: "$$ROOT" }, cond: { $ne: ["$$this.v", null] } } }
}
}
},
/** Replace 'doc' object as root of document */
{
$replaceRoot: { newRoot: "$doc" }
}
],
{ multi: true }
);
测试: mongoplayground
参考: update-with-an-aggregation-pipeline , aggregation-pipeline
注意:
我相信这将是一次性操作,将来您可以使用Joi npm 包或猫鼬模式验证器来限制将null 写入字段值。如果您可以列出您的字段名称,就好像没有太多加上数据集大小太高,那么请尝试使用 $$REMOVE 的聚合,正如“@thammada”所建议的那样。
到目前为止,.updateMany() 中的聚合管道不受许多客户端的支持,即使是少数 mongo shell 版本 - 当时我的票通过使用 .update() 解决了,如果它不起作用,请尝试使用update + { multi : true }.