问题描述
我正在尝试获取具有最大值的文档列表.如果我知道具有最大值的文档数,我可以指定它(就像在另一个 stackoverflow 解决方案mongodb 如何从集合中获取最大值"中的解决方案中一样),但如果我不知道该怎么做,我可以指定它不知道文档的数量是多少.
例如使用以下文件:
{name:"a", age:10}{姓名:b",年龄:11}{姓名:d",年龄:12}{名称:c",年龄:12}
所以我知道有 2 个文档的最大年龄为 12.因此我可以编写以下查询
db.collection.find().sort({age: -1).limit(2)
我使用 limit(2)
是因为我知道有 2 个文档具有最大值,但是我该如何自动化呢?我可以计算具有最大值的记录,将其存储在一个变量中并像 limit(n)
一样使用它吗?还有其他方法吗?
可以使用聚合框架获取结果
var group = {$group:{_id:"$age", names:{$push:"$name"}, count:{$sum:1}}}var sort = {$sort:{"_id":-1}}var limit= {$limit:1}db.selrac.aggregate([组、排序、限制])
输出如下所示:
{_id":12.0,姓名":["d",C"],计数":2.0}
或者如果需要有完整的文档参考替换组:
var group = {$group:{_id:"$age", fullDocument:{$push:"$$ROOT"}, count:{$sum:1}}}
输出:
{_id":12.0,完整文档":[{"_id" : ObjectId("57509a890d4ae20f6de06657"),名称":d",年龄":12.0},{"_id" : ObjectId("57509a890d4ae20f6de06658"),"名称" : "c",年龄":12.0}],计数":2.0}
欢迎任何评论!
I'm trying to get a list of documents that have the max value. I can specify it if I know the number of documents with max value (like in the solution in this another stackoverflow solution 'mongodb how to get max value from collections'), but I don't know how to do it if I don't know what the number of documents is.
For example, using the following documents:
{name:"a", age:10}
{name:"b", age:11}
{name:"d", age:12}
{name:"c", age:12}
So I know that there are 2 documents with max age of 12. Therefore I can write the following query
db.collection.find().sort({age: -1).limit(2)
I use limit(2)
because I know that there are 2 documents with a max value, but how can I automate that? Can I count the records with max value, store it in a variable and use it like limit(n)
? Is there any other way to do it?
you can use aggregation framework to get results
var group = {$group:{_id:"$age", names:{$push:"$name"}, count:{$sum:1}}}
var sort = {$sort:{"_id":-1}}
var limit= {$limit:1}
db.selrac.aggregate([group, sort, limit])
and output looks like this:
{
"_id" : 12.0,
"names" : [
"d",
"c"
],
"count" : 2.0
}
or if there is a need to have full document reference replace group by this:
var group = {$group:{_id:"$age", fullDocument:{$push:"$$ROOT"}, count:{$sum:1}}}
{
"_id" : 12.0,
"fullDocument" : [
{
"_id" : ObjectId("57509a890d4ae20f6de06657"),
"name" : "d",
"age" : 12.0
},
{
"_id" : ObjectId("57509a890d4ae20f6de06658"),
"name" : "c",
"age" : 12.0
}
],
"count" : 2.0
}
Any comments welcome!
这篇关于MongoDB查找并返回所有最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!