mongodb 如何在mongodb中找到最小值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6360465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find min value in mongodb
提问by atbebtg
How do you do the equivalent of
你怎么做相当于
SELECT
MIN(Id) AS MinId
FROM
Table
with MongoDB?
用 MongoDB?
It looks like I will have to use MapReduce but I can't find any example that shows how to do this.
看起来我将不得不使用 MapReduce,但我找不到任何显示如何执行此操作的示例。
回答by dcrosta
You can use a combination of sort
and limit
to emulate min
:
您可以使用组合sort
和limit
效仿min
:
> db.foo.insert({a: 1})
> db.foo.insert({a: 2})
> db.foo.insert({a: 3})
> db.foo.find().sort({a: 1}).limit(1)
{ "_id" : ObjectId("4df8d4a5957c623adae2ab7e"), "a" : 1 }
sort({a: 1})
is an ascending (minimum-first) sort on the a
field, and we then only return the first document, which will be the minimum value for that field.
sort({a: 1})
是对a
字段的升序(最小优先)排序,然后我们只返回第一个文档,这将是该字段的最小值。
EDIT:note that this is written in the mongo shell, but you can do the same thing from C# or any other language using the appropriate driver methods.
编辑:请注意,这是在 mongo shell 中编写的,但是您可以使用适当的驱动程序方法从 C# 或任何其他语言中执行相同的操作。
回答by wanghao
The first
首先
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") }
])
The second, find the min value
二、求最小值
db.sales.aggregate(
[
{
$group:
{
_id: {},
minPrice: { $min: "$price" }
}
}
]
);
result is
结果是
{ "_id" : { }, "minPrice" : 5 }
You can also use min function like this.
您也可以像这样使用 min 函数。
db.sales.aggregate(
[
{
$group:
{
_id: "$item",
minQuantity: { $min: "$quantity" }
}
}
]
)
result are
结果是
{ "_id" : "xyz", "minQuantity" : 5 }
{ "_id" : "jkl", "minQuantity" : 1 }
{ "_id" : "abc", "minQuantity" : 2 }
$min is an accumulator operator available only in the $group stage.
$min 是仅在 $group 阶段可用的累加器运算符。
UPDATE:Changed in version 3.2: $min is available in the $group and $project stages. In previous versions of MongoDB, $min is available in the $group stage only.
更新:在 3.2 版中更改:$min 在 $group 和 $project 阶段可用。在以前版本的 MongoDB 中, $min 仅在 $group 阶段可用。
回答by Andrew Orsich
Just want to show how it can be done with official c# driver (since question about mongodb csharp) with one improvement: I am loading only one field, but not entire document if i want just find Min value of that field. Here is complete test case:
只是想展示如何使用官方 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();
}
And Item
class :
和Item
班级:
public class Item
{
public Item()
{
Id = ObjectId.GenerateNewId();
}
[BsonId]
public ObjectId Id { get; set; }
public int IntValue { get; set; }
public string SomeOtherField { get; set; }
}
Update:Always trying to move further, so, here is extention method for finding min value within collection:
更新:总是试图更进一步,因此,这里是在集合中查找最小值的扩展方法:
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
}
}
So above test case with this extention method can be rewrited like this:
所以上面使用这种扩展方法的测试用例可以像这样重写:
[TestMethod]
public void Test()
{
var _mongoServer = MongoServer.Create("mongodb://localhost:27020");
var database = _mongoServer.GetDatabase("StackoverflowExamples");
var col = database.GetCollection("items");
var minValue = col.FindMinValue("IntValue");
Assert.AreEqual(1, minValue);
col.RemoveAll();
}
Hope someone will use it ;).
希望有人会使用它;)。