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"
}
4
  • 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 or as an alternative the 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. Commented Aug 31, 2019 at 1: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". Commented Aug 31, 2019 at 1: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) }) Commented Aug 31, 2019 at 2: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's answer Commented Oct 15, 2019 at 22:41

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.