Last active
April 29, 2024 15:09
-
-
Save olivier5741/fcdbdfae22ff9f25ffcfc9a1763a6ad9 to your computer and use it in GitHub Desktop.
Clean up null values in mongo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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