0

How to add dynamically calculated filed/column to the result-set documents? I don't need aggregation but if that's the only way with Mongo... yet I'm having troubles with $project aggregation stage. How to pass filed value(s) to a (non-aggregating) JS function in $project stage?

I'm looking for a way to transform the following to MongoDB query:

SELECT CountryName, MD5(CountryName) as md5 FROM Country

I've tried aggregation

db.getCollection('Country').aggregate([
{ "$project":{ a: "$Abbreviation", b: hex_md5("$Abbreviation")} }
])

Expected:

{
    "_id" : 1.0,
    "a" : "US",
    "b" : "7516FD43ADAA5E0B8A65A672C39845D2"
},
{
    "_id" : 2.0,
    "a" : "JP",
    "b" : "24D22E03AFB23EDB45C6C8CFA16A280E"
}
// but I get "$Abbreviation" treated as a string instead - not replaced by actual field value(s)
// MD5("$Abbreviation") == 668eddfec9d4b8a3bb099aca67b365d8
{
    "_id" : 1.0,
    "a" : "US",
    "b" : "668eddfec9d4b8a3bb099aca67b365d8"
},
{
    "_id" : 2.0,
    "a" : "JP",
    "b" : "668eddfec9d4b8a3bb099aca67b365d8"
}
J. Doe
  • 1
  • 2
  • 1
    `aggregate()` cannot use external functions to apply to values of a document in an executed aggregation pipeline. You can only use the available [Aggregation Pipeline Operators](https://docs.mongodb.com/manual/reference/operator/aggregation/) or as an alternative the [`mapReduce()`](https://docs.mongodb.com/manual/reference/method/db.collection.mapReduce/) can execute any JavaScript expression, BUT this **must** be fully defined within the JavaScript methods. In this case, you would need to include the necessary JavaScript code to produce the MD5 hash you want. – Neil Lunn Aug 31 '19 at 01:34
  • 1
    In short, MongoDB does not have a "built in" `MD5()` method like the SQL database you were using does. This is "by design". – Neil Lunn Aug 31 '19 at 01:35
  • @J.Doe : Please try this ::::> db.getCollection('yourCollection').aggregate([{$project :{a: '$Abbreviation', md5 : '$Abbreviation'}}]).forEach((data)=>{ data.md5 = hex_md5(data.md5); print(data) }) – whoami - fakeFaceTrueSoul Aug 31 '19 at 02:10
  • Note: this is NOT a duplicate, at least NOT to the suggested questions/topics! The question is not about how to aggregate nor about how to generate MD5 hash! The question is 'How to add dynamically calculated filed/column' to the result(set), so I'll accept [srinivasy](https://stackoverflow.com/users/7237613/srinivasy)'s answer – J. Doe Oct 15 '19 at 22:41

0 Answers0