0

I'm trying to update some fields in the MongoDB Shell using the aggregation framework. I actually am wanting to convert the ip addresses currently as a String type in the collection into a Long type and so need to convert the following scala code into MongoDB command:

   def ipv4ToLong(ip: String): Option[Long] = Try(
     ip.split('.').ensuring(_.length == 4)
       .map(_.toLong).ensuring(_.forall(x => x >= 0 && x < 256))
       .reverse.zip(List(0,8,16,24)).map(xi => xi._1 << xi._2).sum
   ).toOption

I've been able to convert most of this using the MongoDB Aggregation documentation but I am having some trouble with this part: xi._1 << xi._2

From the my IDE prompts; I can see that this (<<) is a synthetic function relating to scala byte (as seen here) and is defined as:

Returns this value bit-shifted left by the specified number of bits, filling in the new right bits with zeroes.

Any idea if there is a similar function to use in the MongoDB commands or operators? Or an alternative solution.

1 Answers1

0

I hate answering my own question - it's always better if someone can help out but sadly not on this occasion and it might save someone some time. I was eventually able to locate some more information about bit-shift operators here. I can see that the function << takes two numerical types (e.g. Long, Int, etc) and as suggested the bits are shifted to the left. As mentioned; I am trying to equate this to implement in MongoDB as there isn't an equivalent function. But that link was effective in breaking this down. So:

    a << b = a * 2^b

And using MongoDB operators (as originally intended) this would be:

    $multiply: [a, { $pow: [2, b]}]