[英]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.在MongoDB中,我想获取出现次数最少的字段的值。
Example 1: If I have a field called version
, 20 documents/entries use version 2, 30 use version 3 and 5 use version 1.示例 1:如果我有一个名为
version
的字段,则 20 个文档/条目使用版本 2,30 个使用版本 3,5 个使用版本 1。
I want to get what version is the least used.我想获得最少使用的版本。 So, with example 1, it should return version 1.
因此,对于示例 1,它应该返回版本 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示例 2:30 个文档/条目使用版本 1.0.5,10 个使用 1.0.2,7 个使用 1.0.8,11 个使用 1.0.1
In this example, it should return 1.0.8 since that is in the document 7 times.在此示例中,它应该返回 1.0.8,因为它在文档中出现了 7 次。
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.
某些版本可能有“alpha 1.0.8”之类的东西。 I need to just get the numbers.
我只需要得到数字。
Simple $group->$sort->$limit can do the task:简单的 $group->$sort->$limit 可以完成任务:
db.collection.aggregate([
{
$group: {
_id: "$version",
occurance: {
$sum: 1
}
}
},
{
$sort: {
occurance: 1
}
},
{
$limit: 1
}
])
Explained:解释:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.