【问题标题】:What is MongoDB's $min? How is that different from find().sort({the_field: 1}).limit(1)?MongoDB 的 $min 是多少?这与 find().sort({the_field: 1}).limit(1) 有何不同?
【发布时间】:2016-01-01 15:49:25
【问题描述】:

MongoDB 的 aggregation $minquery modifier $minfind().sort() 之间的区别是什么?db.the_collection.find().sort({the_field:1}).limit(1) 返回 the_field 的最小值?

如果每分钟有大约几百次调用来检索集合中的最小元素并每次独立处理它,我应该使用哪一个?

附带问题:有人可以使用 $min 向我展示正确的语法,以便为我提供集合中字段的最小值吗? db.the_collection.find().min({the_field:10}) 不起作用。

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    要获得“the_field”的最低值的文档,您应该使用 db.the_collection.find().sort({the_field:1}).limit(1) 所以在这里我们首先对文档进行排序,然后从查询中看到第一个文档。

    聚合 $min :
    当我们将文档分组为单个文档并且我们希望将该单个文档的值保持在它所在的所有文档中的最小值时使用它。

    $min 运算符:
    它用于特定索引的包容性下限,以约束 find() 的结果。简单来说,如果 the_field 被索引并且我们想对 find() 保持一些约束,那么我们可以使用它。它通常用于提高性能。
    您输入的语法是正确的,但它需要一个索引字段,结果将与您实际想要的不同。

    【讨论】:

    • 嗨想象一下,我已经通过 the_field 索引了我的收藏并使用了db.the_collection.find().min({the_field:10}),但得到了错误:... Sort: {}\nProj: {}\n planner returned error: unable to find relevant index for max/min query","code" : 17007
    • @Melissa :这是获取 the_field db.the_collection.find().sort({the_field:1}).limit(1) 列的最小值 rwo 的查询。 $min 运算符用于查找查询被索引时的性能改进,与获取 the_field 的最小行无关。
    • 哇,感谢imagin 这么快的回复!我已经通过 the_field 应用了索引,所以如果我每分钟调用数百次 db.the_collection.find().sort({the_field:1}).limit(1) 可以吗?我希望数据库不要重复排序。
    • 是的,它不会产生任何问题。
    • 要提高性能,您可以参考此链接:docs.mongodb.org/manual/tutorial/…
    【解决方案2】:

    因为 min() 需要字段上的索引,并强制查询使用该索引,即使有更好的索引可供选择, 因此,如果可能,您必须更喜欢 $gte 或查询的排序操作。

    db.the_collection.find().sort({the_field:1}).limit(1)
    

    所以上面的查询最好是使用 $min 操作作为比较。

    请参阅下面提到的链接。 http://docs.mongodb.org/manual/reference/operator/meta/min/#interaction-with-index-selection

    在无索引键上运行 min 运算符时,会出现以下错误

    Error: error: {
        "$err" : "Unable to execute query: error processing query: ns=db.dbName limit=0 skip=0\nTree: status == \"approved\"\nSort: {}\nProj: {}\n planner returned error: unable to find relevant index for max/min query",
        "code" : 17007
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-20
      • 2015-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多