Count unique values within model's Array in MongoDB

后端 未结 1 2024
灰色年华
灰色年华 2021-01-24 17:10

What is the best way to just COUNT unique values within many model\'s array? Let\'s say my Model is like this:

{
  myKey: [
    \"idnumber1000\",
    \"idnumber1         


        
相关标签:
1条回答
  • 2021-01-24 17:26

    You can do this with a simple 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) {...}
    );
    
    0 讨论(0)
提交回复
热议问题