MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Conta i valori univoci all'interno dell'array del modello in MongoDB

Puoi farlo con un semplice aggregate pipeline:

MyModel.aggregate([
    // Project just the myKey field as that's all that's needed
    {$project: {_id: 0, myKey: 1}},
    // Duplicate each doc, once per myKey element
    {$unwind: '$myKey'},
    // Group on myKey and get a count
    {$group: {_id: '$myKey', count: {$sum: 1}}}
  ],
  function(err, results) {...}
);