How can I remove all fields that are null
from all documents of a given collection?
I have a collection of documents such as:
{
Starting Mongo 4.2
, db.collection.update() can accept an aggregation pipeline, finally allowing the removal of a field based on its value:
// { _id: ObjectId("5d0e8...d2"), property1: "value1", property2: "value2" }
// { _id: ObjectId("5d0e8...d3"), property1: "value1", property2: null, property3: "value3" }
db.collection.update(
{},
[{ $replaceWith: {
$arrayToObject: {
$filter: {
input: { $objectToArray: "$$ROOT" },
as: "item",
cond: { $ne: ["$$item.v", null] }
}
}
}}],
{ multi: true }
)
// { _id: ObjectId("5d0e8...d2"), property1: "value1", property2: "value2" }
// { _id: ObjectId("5d0e8...d3"), property1: "value1", property3: "value3" }
In details:
The first part {}
is the match query, filtering which documents to update (in our case all documents).
The second part [{ $replaceWith: { ... }]
is the update aggregation pipeline (note the squared brackets signifying the use of an aggregation pipeline):
[{ k: "property1", v: "value1" }, { k: "property2", v: null }, ...]
.v
is null
.Don't forget { multi: true }
, otherwise only the first matching document will be updated.