복붙노트

[MONGODB] MongoDB의에서 최소값을 찾는 방법

MONGODB

MongoDB의에서 최소값을 찾는 방법

당신은 어떻게에 해당합니까

SELECT 
  MIN(Id) AS MinId
FROM
  Table

MongoDB를 가진?

내가 맵리 듀스를 사용해야 할 것입니다하지만 난 쇼가 어떻게이 작업을 수행하는 것을 어떤 예를 찾을 수없는 것 같습니다.

해결법

  1. ==============================

    1.당신은 에뮬레이션 분에 종류와 제한의 조합을 사용할 수 있습니다 :

    당신은 에뮬레이션 분에 종류와 제한의 조합을 사용할 수 있습니다 :

    > 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 }
    

    정렬 ({A : 1}) 상승 (최소 제) 정렬 필드에이며, 우리는 해당 필드의 최소값이 될 제 문서를 반환한다.

    편집 :이이 몽고 쉘에서 작성된 것입니다,하지만 당신은 C # 또는 적합한 드라이버 방법을 사용하여 다른 언어에서 같은 일을 할 수있는 참고.

  2. ==============================

    2.첫번째

    첫번째

      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 }
    

    당신은 또한 다음과 같은 분 기능을 사용할 수 있습니다.

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

    있는 결과

    { "_id" : "xyz", "minQuantity" : 5 }
    { "_id" : "jkl", "minQuantity" : 1 }
    { "_id" : "abc", "minQuantity" : 2 }
    

    $ 분 만 $ 조별 가능 누산기 연산자이다.

    최신 정보: 버전 3.2에서 변경 : $ 분은 $ 그룹과 $ 프로젝트 단계에서 사용할 수 있습니다. MongoDB를 이전 버전의 $ 분 만 $ 조별 리그에서 사용할 수 있습니다.

    자세한 도움말을 보려면 여기를 클릭

  3. ==============================

    3.난 그냥 그 분야의 최소 값을 찾을하려는 경우 전체 문서를 나는 단지 하나의 필드를 로딩하고 있지만 : 그냥 하나 개 개선과 (MongoDB를의 CSHARP에 대한 질문부터) 공식 C #을 드라이버와 함께 할 수있는 방법을 보여주고 싶어요. 여기에 완전한 테스트 케이스는 다음과 같습니다

    난 그냥 그 분야의 최소 값을 찾을하려는 경우 전체 문서를 나는 단지 하나의 필드를 로딩하고 있지만 : 그냥 하나 개 개선과 (MongoDB를의 CSHARP에 대한 질문부터) 공식 C #을 드라이버와 함께 할 수있는 방법을 보여주고 싶어요. 여기에 완전한 테스트 케이스는 다음과 같습니다

    [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();
    } 
    

    그리고 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; }
    }
    

    업데이트 : 항상 여기에 수집 내에서 최소값을 찾기위한 확장 방법, 더 이동하려고 :

    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
        }
    }
    

    이 확장 방법에 따라서 위의 테스트 케이스는 다음과 같이 쓸 수있다 :

    [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();
    }
    

    희망 누군가가 그것을 사용합니다).

  4. from https://stackoverflow.com/questions/6360465/how-to-find-min-value-in-mongodb by cc-by-sa and MIT license