Mark G
Mark G

Reputation: 13

MongoDB query for distinct field values that meet a conditional

I have a collection named 'sentences'. I would like a list of all the unique values of 'last_syls' where the number of entries containing that value of 'last_syls' is greater than 10.

A document in this collection looks like:

{ "_id" : ObjectId( "51dd9011cf2bee3a843f215a" ),
  "last_syls" : "EY1D",
  "last_word" : "maid"}

I've looked into db.sentences.distinct('last_syls'), but cannot figure out how to query based on the count for each of these distinct values.

Upvotes: 1

Views: 2399

Answers (1)

Chris Heald
Chris Heald

Reputation: 62638

You're going to want to use the aggregation framework:

db.sentences.aggregate([
  {
    $group: {
      _id: "$last_syls",
      count: { $sum: 1}
    }
  },
  {
    $match: {
      count: { $gt: 10 }
    }
  }
])

This groups documents by their last_syls field with a count per group, then filters that result set to all results with a count greater than 10.

Upvotes: 2

Related Questions