To optimize the process, it is recommended to identify all potential keys in advance and then execute a single update command using the multi-parameter to eliminate all identified keys. The methodology may vary depending on the version of MongoDB being used.
Approach for MongoDB 3.4: $objectToArray
let fields = db.teamList.aggregate([
{ "$project": {
"_id": 0,
"fields": {
"$map": {
"input": {
"$filter": {
"input": { "$objectToArray": "$$ROOT" },
"as": "d",
"cond": { "$eq": [{ "$substrCP": [ "$$d.k", 0, 4 ] }, "team" ] }
}
},
"as": "f",
"in": "$$f.k"
}
}
}},
{ "$unwind": "$fields" },
{ "$group": { "_id": "$fields" } }
])
.map( d => ({ [d._id]: "" }))
.reduce((acc,curr) => Object.assign(acc,curr),{})
db.teamList.updateMany({},{ "$unset": fields });
The aggregate() function transforms the document fields into an array using $objectToArray, filters out only the ones with keys starting with "team", and then generates a unique list of these matching fields through unwind and group operations.
The subsequent steps convert this list into a single object and utilize $unset to remove these fields from all documents.
For Earlier Versions: mapReduce
var fields = db.teamList.mapReduce(
function() {
Object.keys(this).filter( k => /^team/.test(k) )
.forEach( k => emit(k,1) );
},
function() {},
{ "out": { "inline": 1 } }
)
.results.map( d => ({ [d._id]: "" }))
.reduce((acc,curr) => Object.assign(acc,curr),{})
db.teamList.update({},{ "$unset": fields },{ "multi": true });
A similar approach is used, with the only distinction being the utilization of update() instead of updateMany() for versions lacking the latter method, specifying the "multi" parameter to affect all matched documents.
Advanced Options
Exhausting all documents just to delete fields is not recommended. Therefore, the aforementioned methods are preferred. However, constructing an extensive list of keys might surpass the 16MB BSON limit in rare cases.
Two potential extensions to the techniques include using the cursor with aggregate() to process fields in batches and creating a temporary collection with mapReduce() to iteratively handle distinct field names.
If you are aware of all the field names in advance, you can directly specify them in the update statement without the need for elaborate calculations.