简体   繁体   中英

How do I get a value from a field that is least common in database?

In MongoDB, I want to get the value of a field that occurs the least amount of times.

Example 1: If I have a field called version , 20 documents/entries use version 2, 30 use version 3 and 5 use version 1.

I want to get what version is the least used. So, with example 1, it should return version 1.

Example 2: 30 documents/entries use version 1.0.5, 10 use 1.0.2, 7 use 1.0.8 and 11 use 1.0.1

In this example, it should return 1.0.8 since that is in the document 7 times.

How can I do something like this?

I hope this makes sense.

OH, I forgot to mention, sometimes the version could have words before them. so I need to only sort by numbers. Some version might have stuff like 'alpha 1.0.8' and such. I need to just get the numbers.

Simple $group->$sort->$limit can do the task:

db.collection.aggregate([
{
 $group: {
  _id: "$version",
  occurance: {
    $sum: 1
  }
 }
},
 {
  $sort: {
    occurance: 1
   }
 },
 {
  $limit: 1
 }
])

Explained:

  1. Group by version value to get the occurance for all documents.
  2. Sort in ASCENDING order.
  3. Limit the result to 1st document ( this version will be least used )

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM