MongoDB is it possible to runCommand distinct with substr on key

232 Views Asked by At

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 } }},
   }
)
1

There are 1 best solutions below

0
Buzz Moschetti On BEST ANSWER

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} }}
  ]);