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:
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.