Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Add MD5 hash value to MongoDB collection?
To add MD5 hash values to a MongoDB collection, use the hex_md5() function combined with forEach() to iterate through documents and generate hash values for specific fields like passwords.
Syntax
db.collection.find().forEach(function(doc) {
doc.hashField = hex_md5(doc.sourceField);
db.collection.save(doc);
});
Sample Data
db.addMd5HashValueDemo.insertMany([
{"UserName": "Adam", "UserPassword": "Adam123456"},
{"UserName": "Chris", "UserPassword": "Chris_121#"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd6a4c66d78f205348bc619"),
ObjectId("5cd6a4e46d78f205348bc61a")
]
}
Display the original documents ?
db.addMd5HashValueDemo.find();
{ "_id": ObjectId("5cd6a4c66d78f205348bc619"), "UserName": "Adam", "UserPassword": "Adam123456" }
{ "_id": ObjectId("5cd6a4e46d78f205348bc61a"), "UserName": "Chris", "UserPassword": "Chris_121#" }
Add MD5 Hash Values
Generate MD5 hash for each user's password and store it in a new field ?
db.addMd5HashValueDemo.find().forEach(function(documentPass) {
documentPass.Value = hex_md5(documentPass.UserPassword);
db.addMd5HashValueDemo.save(documentPass);
});
Verify Results
db.addMd5HashValueDemo.find();
{ "_id": ObjectId("5cd6a4c66d78f205348bc619"), "UserName": "Adam", "UserPassword": "Adam123456", "Value": "6523857c2bf79b63fd5fa0322575f7be" }
{ "_id": ObjectId("5cd6a4e46d78f205348bc61a"), "UserName": "Chris", "UserPassword": "Chris_121#", "Value": "3391ccbe33624258cafa23aa50301615" }
Key Points
- The
hex_md5()function generates a 32-character hexadecimal MD5 hash. - Use
forEach()to process multiple documents in batch operations. - The hash is stored as a new field while preserving the original password field.
Conclusion
MongoDB's hex_md5() function enables easy generation of MD5 hashes for any string field. Combine it with forEach() to add hash values to existing collections efficiently.
Advertisements
