atb*_*btg 37 mongodb mongodb-.net-driver
你怎么做相当于
SELECT
MIN(Id) AS MinId
FROM
Table
Run Code Online (Sandbox Code Playgroud)
在MongoDB中.看起来我将不得不使用MapReduce,但我找不到任何显示如何执行此操作的示例.
谢谢.
dcr*_*sta 66
您可以使用组合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 }
Run Code Online (Sandbox Code Playgroud)
sort({a: 1})是a字段上的升序(最小 - 第一)排序,然后我们只返回第一个文档,该文档将是该字段的最小值.
编辑:请注意,这是在mongo shell中编写的,但您可以使用适当的驱动程序方法从C#或任何其他语言执行相同的操作.
wan*_*hao 13
首先
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") }
])
Run Code Online (Sandbox Code Playgroud)
第二,找到最小值
db.sales.aggregate(
[
{
$group:
{
_id: {},
minPrice: { $min: "$price" }
}
}
]
);
Run Code Online (Sandbox Code Playgroud)
结果是
{ "_id" : { }, "minPrice" : 5 }
Run Code Online (Sandbox Code Playgroud)
你也可以像这样使用min函数.
db.sales.aggregate(
[
{
$group:
{
_id: "$item",
minQuantity: { $min: "$quantity" }
}
}
]
)
Run Code Online (Sandbox Code Playgroud)
结果是
{ "_id" : "xyz", "minQuantity" : 5 }
{ "_id" : "jkl", "minQuantity" : 1 }
{ "_id" : "abc", "minQuantity" : 2 }
Run Code Online (Sandbox Code Playgroud)
$ min是仅在$ group阶段可用的累加器运算符.
更新: 版本3.2中已更改:$ min和$ project阶段中提供了$ min.在早期版本的MongoDB中,$ min仅在$ group阶段可用.
只是想展示如何使用官方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();
}
Run Code Online (Sandbox Code Playgroud)
和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; }
}
Run Code Online (Sandbox Code Playgroud)
更新:总是试图进一步移动,所以,这里是在集合中查找最小值的扩展方法:
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
}
}
Run Code Online (Sandbox Code Playgroud)
因此,使用此扩展方法的上述测试用例可以像这样重写:
[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();
}
Run Code Online (Sandbox Code Playgroud)
希望有人会使用它;).
| 归档时间: |
|
| 查看次数: |
45020 次 |
| 最近记录: |