MongoDB runCommand distinct with substr on key 是否可以

MongoDB is it possible to runCommand distinct with substr on key

是否可以在我定位的键上运行 runCommand distinct with substr? 我不断收到 missing : after property id :

db.runCommand(
   {
       distinct: "mycollection",
       key: {"myfield" : { $substr: { "$myfield", 0, 10 } }},
   }
)

无法使用 runCommand distinct 执行此操作。您需要使用 agg 框架来处理该字段,然后使用 $group 获取不同的值,因此:

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

获取这些不同值的计数通常很有用:

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