如何在mongodb中找到最小值

如何在mongodb中找到最小值,mongodb,mongodb-.net-driver,Mongodb,Mongodb .net Driver,你是如何做到这一点的 选择 MINId作为MINId 从…起 桌子 和MongoDB 看起来我必须使用MapReduce,但我找不到任何示例来说明如何执行此操作。您可以使用排序和限制的组合来模拟min: sort{a:1}是对a字段的第一个最小升序排序,然后我们只返回第一个文档,它将是该字段的最小值 编辑:请注意,这是在mongo shell中编写的,但您可以使用适当的驱动程序方法从C或任何其他语言执行相同的操作。只想展示如何使用官方C驱动程序执行此操作,因为关于mongodb csharp的问

你是如何做到这一点的

选择 MINId作为MINId 从…起 桌子 和MongoDB


看起来我必须使用MapReduce,但我找不到任何示例来说明如何执行此操作。

您可以使用排序和限制的组合来模拟min:

sort{a:1}是对a字段的第一个最小升序排序,然后我们只返回第一个文档,它将是该字段的最小值


编辑:请注意,这是在mongo shell中编写的,但您可以使用适当的驱动程序方法从C或任何其他语言执行相同的操作。

只想展示如何使用官方C驱动程序执行此操作,因为关于mongodb csharp的问题有一个改进:我只加载了一个字段,但不是整个文档,如果我只想找到该字段的最小值。以下是完整的测试用例:

[TestMethod]
public void Test()
{
  var _mongoServer = MongoServer.Create("mongodb://localhost:27020");
  var database = _mongoServer.GetDatabase("StackoverflowExamples");
  var col = database.GetCollection("items");

  //Add test data
  col.Insert(new Item() { IntValue = 1, SomeOtherField = "Test" });
  col.Insert(new Item() { IntValue = 2 });
  col.Insert(new Item() { IntValue = 3 });
  col.Insert(new Item() { IntValue = 4 });

  var item = col.FindAs<Item>(Query.And())
  .SetSortOrder(SortBy.Ascending("IntValue"))
  .SetLimit(1)
  .SetFields("IntValue") //here i loading only field that i need
  .Single();
  var minValue = item.IntValue;

  //Check that we found min value of IntValue field
  Assert.AreEqual(1, minValue);
  //Check that other fields are null in the document
  Assert.IsNull(item.SomeOtherField);
  col.RemoveAll();
} 
更新:始终尝试进一步移动,因此,以下是在集合中查找最小值的扩展方法:

public static class MongodbExtentions
{
    public static int FindMinValue(this MongoCollection collection, string fieldName)
    {
        var cursor = collection.FindAs<BsonDocument>(Query.And())
                     .SetSortOrder(SortBy.Ascending(fieldName))
                     .SetLimit(1)
                     .SetFields(fieldName);

        var totalItemsCount = cursor.Count();

        if (totalItemsCount == 0)
            throw new Exception("Collection is empty");

        var item = cursor.Single();

        if (!item.Contains(fieldName))
            throw new Exception(String.Format("Field '{0}' can't be find within '{1}' collection", fieldName, collection.Name));

        return item.GetValue(fieldName).AsInt32; // here we can also check for if it can be parsed
    }
}
希望有人会使用它

第一个

  db.sales.insert([
    { "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") },
    { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") },
    { "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") },
    { "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") },
    { "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }
  ])
第二,找到最小值

  db.sales.aggregate(
   [
     {
       $group:
       {
         _id: {},
         minPrice: { $min: "$price" }
       }
     }
   ]
  );
结果是

{ "_id" : {  }, "minPrice" : 5 }
您也可以像这样使用min函数

 db.sales.aggregate(
    [
      {
        $group:
        {
          _id: "$item",
          minQuantity: { $min: "$quantity" }
        }
      }
    ]
  )
结果是

{ "_id" : "xyz", "minQuantity" : 5 }
{ "_id" : "jkl", "minQuantity" : 1 }
{ "_id" : "abc", "minQuantity" : 2 }
$min是仅在$group阶段可用的累加器运算符

更新: 在版本3.2中更改:$min在$group和$project阶段中可用。在以前版本的MongoDB中,$min仅在$group阶段可用


非常感谢。我正要为c语言编写代码driver@atbebtg:不客气。就在一秒钟前,我更新了我的答案,所以我创建了用于查找最小值的扩展方法@安德烈·奥西奇:哇!我不知道还能说什么。再次感谢你们!别担心,我肯定会使用这个函数:注意:对于任何大型数据集,您可能都需要在{a:1}上建立索引。这仍然是获得最小值的最佳方法吗?您现在可以使用聚合框架来实现这个结果。见下面王浩的答案。db.myCollection.aggregate[{$group:{{u id:{},minPrice:{$min:$price}}];错误:它可以在$project阶段使用。检查您链接到的文档。这比接受的答案慢得多。如果对特定字段进行索引,则find.sortquery几乎是即时的。
{ "_id" : {  }, "minPrice" : 5 }
 db.sales.aggregate(
    [
      {
        $group:
        {
          _id: "$item",
          minQuantity: { $min: "$quantity" }
        }
      }
    ]
  )
{ "_id" : "xyz", "minQuantity" : 5 }
{ "_id" : "jkl", "minQuantity" : 1 }
{ "_id" : "abc", "minQuantity" : 2 }