0

Is it possible to runCommand distinct with substr on the key I'm targeting? I keep getting missing : after property id :

db.runCommand(
   {
       distinct: "mycollection",
       key: {"myfield" : { $substr: { "$myfield", 0, 10 } }},
   }
)
Daniel S
  • 621
  • 3
  • 8
  • 18

1 Answers1

0

Can't do this with runCommand distinct. You need to use the agg framework to process the field and then get distinct values using $group, thusly:

db.foo.aggregate([
{$group: {_id: {$substr: [ "$myfield",0,10]} }}
  ]);

Very often it is useful to get the count of those distinct values:

db.foo.aggregate([
{$group: {_id: {$substr: ["$myfield",0,10]}, count: {$sum:1} }}
  ]);

Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33