복붙노트

[MONGODB] MongoDB의 결과를 제한하지만 여전히 전체 수를 점점?

MONGODB

MongoDB의 결과를 제한하지만 여전히 전체 수를 점점?

속도를 위해, 나는 10의 결과로 쿼리를 제한하고 싶습니다

db.collection.find( ... ).limit(10)

그러나, 나는 그렇게 말하고, 총 수를 알고 싶습니다 또한 거라고 "가 124이었다 그러나 나는 10이". 이 작업을 수행하는 것이 효율적인 방법이 있나요?

해결법

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

    1.기본적으로, 수 () 제한 ()와 카운트 전체 쿼리의 결과를 무시합니다. 그래서 당신은 예를 들어,이 작업을 수행 할 때, var에 A = db.collection.find (...) 한계 (10).; a.count을 실행하는 () 당신에게 당신의 쿼리의 총 수를 줄 것이다.

    기본적으로, 수 () 제한 ()와 카운트 전체 쿼리의 결과를 무시합니다. 그래서 당신은 예를 들어,이 작업을 수행 할 때, var에 A = db.collection.find (...) 한계 (10).; a.count을 실행하는 () 당신에게 당신의 쿼리의 총 수를 줄 것이다.

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

    2.카운트 (1)을 수행하여 제한 및 이동을 포함한다.

    카운트 (1)을 수행하여 제한 및 이동을 포함한다.

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

    3.cursor.count ()는 기본적으로 cursor.skip ()와 cursor.limit ()을 무시한다.

    cursor.count ()는 기본적으로 cursor.skip ()와 cursor.limit ()을 무시한다.

    출처 : http://docs.mongodb.org/manual/reference/method/cursor.count/#cursor.count

  4. ==============================

    4.@johnnycrab에 의해 허용 대답은 몽고의 CLI입니다.

    @johnnycrab에 의해 허용 대답은 몽고의 CLI입니다.

    당신은 Node.js를하고 Express.js에서 같은 코드를 작성해야하는 경우, 당신은 toArray의 "결과"와 함께 "계산"기능을 사용할 수 있도록 다음과 같이 사용해야합니다.

    var curFind = db.collection('tasks').find({query});
    

    그럼 당신이 (다른 중첩 한)처럼 이후에 두 가지 기능을 실행할 수 있습니다

    curFind.count(function (e, count) {
    
    // Use count here
    
        curFind.skip(0).limit(10).toArray(function(err, result) {
    
        // Use result here and count here
    
        });
    
    });
    
  5. ==============================

    5.푸시와 슬라이스를 사용하는 솔루션이있다 : https://stackoverflow.com/a/39784851/4752635

    푸시와 슬라이스를 사용하는 솔루션이있다 : https://stackoverflow.com/a/39784851/4752635

    나는 선호한다

    $$ ROOT를 밀어 큰 컬렉션에 대한 16메가바이트의 문서 메모리 제한에 $ 슬라이스 실행을 사용하여와 솔루션. 또한, 대형 컬렉션에 대한 두 개의 쿼리 함께 빠른 $$ ROOT 밀고와 함께보다 실행하는 것 같다. 당신은 (아마도 한 종류) 두 쿼리의 느린에 의해 제한됩니다, 그래서 당신은뿐만 아니라 병렬로 실행할 수 있습니다.

    - (I이 예에서 Node.js를 사용하지만 아이디어는 동일 주) I 2 개 쿼리와 통합 프레임 워크를 사용하여이 솔루션으로 정착

    var aggregation = [
      {
        // If you can match fields at the begining, match as many as early as possible.
        $match: {...}
      },
      {
        // Projection.
        $project: {...}
      },
      {
        // Some things you can match only after projection or grouping, so do it now.
        $match: {...}
      }
    ];
    
    
    // Copy filtering elements from the pipeline - this is the same for both counting number of fileter elements and for pagination queries.
    var aggregationPaginated = aggregation.slice(0);
    
    // Count filtered elements.
    aggregation.push(
      {
        $group: {
          _id: null,
          count: { $sum: 1 }
        }
      }
    );
    
    // Sort in pagination query.
    aggregationPaginated.push(
      {
        $sort: sorting
      }
    );
    
    // Paginate.
    aggregationPaginated.push(
      {
        $limit: skip + length
      },
      {
        $skip: skip
      }
    );
    
    // I use mongoose.
    
    // Get total count.
    model.count(function(errCount, totalCount) {
      // Count filtered.
      model.aggregate(aggregation)
      .allowDiskUse(true)
      .exec(
      function(errFind, documents) {
        if (errFind) {
          // Errors.
          res.status(503);
          return res.json({
            'success': false,
            'response': 'err_counting'
          });
        }
        else {
          // Number of filtered elements.
          var numFiltered = documents[0].count;
    
          // Filter, sort and pagiante.
          model.request.aggregate(aggregationPaginated)
          .allowDiskUse(true)
          .exec(
            function(errFindP, documentsP) {
              if (errFindP) {
                // Errors.
                res.status(503);
                return res.json({
                  'success': false,
                  'response': 'err_pagination'
                });
              }
              else {
                return res.json({
                  'success': true,
                  'recordsTotal': totalCount,
                  'recordsFiltered': numFiltered,
                  'response': documentsP
                });
              }
          });
        }
      });
    });
    
  6. from https://stackoverflow.com/questions/15300882/limiting-results-in-mongodb-but-still-getting-the-full-count by cc-by-sa and MIT license