Skip to content

Instantly share code, notes, and snippets.

@olivier5741
Last active April 29, 2024 15:09
Show Gist options
  • Save olivier5741/fcdbdfae22ff9f25ffcfc9a1763a6ad9 to your computer and use it in GitHub Desktop.
Save olivier5741/fcdbdfae22ff9f25ffcfc9a1763a6ad9 to your computer and use it in GitHub Desktop.
Clean up null values in mongo
const collectionNames = db.getCollectionNames();
for (const name of collectionNames) {
var coll = db.getCollection(name);
var cursor = coll.find();
while (cursor.hasNext()) {
var doc = cursor.next();
var keys = {};
var hasNull = false;
for (var x in doc) {
const json = JSON.stringify()
if (x != "_id" && (doc[x] == null || (Array.isArray(doc[x]) && doc[x].length == 0) || (typeof doc[x] === 'object' && Object.keys(doc[x]).length == 0 ) )) {
keys[x] = 1;
hasNull = true;
}
}
if (hasNull) {
coll.updateOne({ _id: doc._id }, { $unset: keys });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment