Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-39108

Make $limit accept 0 for all documents to be passed

    • Type: Icon: Improvement Improvement
    • Resolution: Won't Fix
    • Priority: Icon: Minor - P4 Minor - P4
    • None
    • Affects Version/s: None
    • Component/s: Aggregation Framework
    • None

      `$limit`, as it is now, accepts positive integers to be passed to limit the documents handed over to the next stage.

      However, to dynamically set up aggregations in programs, one might want to pass a certain amount of documents for testing, while per default all documents should be processed.

      In order to be able to do it now, one needs to modify the structure of the aggregation passed in order to be able to do that. The below example is given in Go, but it is applicable for all the other languages as well, I presume.

      func createAggregationNow(limit int) []bson.M {
      	var agg []bson.M
      
      	agg = []bson.M{
      		bson.M{"$match": bson.M{"date": bson.M{"$lte": time.Now()}}},
      		bson.M{"$sort": bson.M{"date": -1}},
      	}
      
      	if limit > 0 {
      		agg = append(agg, bson.M{"$limit": limit})
      	}
      
      	remaining := []bson.M{
      		bson.M{"$unwind": "$items"},
      		bson.M{"$out": "foobar"},
      	}
      	return append(agg, remaining...)
      }
      

      Accepting 0 as a value for `$limit` which would simply pass all documents would result in cleaner code:

      Unable to find source-code formatter for language: golang. Available languages are: actionscript, ada, applescript, bash, c, c#, c++, cpp, css, erlang, go, groovy, haskell, html, java, javascript, js, json, lua, none, nyan, objc, perl, php, python, r, rainbow, ruby, scala, sh, sql, swift, visualbasic, xml, yaml
      func createAggregationBetter(limit int) []bson.M {
      	return []bson.M{
      		bson.M{"$match": bson.M{"date": bson.M{"$lte": time.Now()}}},
      		bson.M{"$sort": bson.M{"date": -1}},
      		bson.M{"$limit": limit},
      		bson.M{"$unwind": "$items"},
      		bson.M{"$out": "foobar"},
      	}
      }
      

      I guess a `$limit` with value 0 could actually be optimized out of the pipeline when it is parsed, but that is just a guess.

            Assignee:
            asya.kamsky@mongodb.com Asya Kamsky
            Reporter:
            markus.mahlberg@icloud.com Markus Mahlberg
            Votes:
            0 Vote for this issue
            Watchers:
            10 Start watching this issue

              Created:
              Updated:
              Resolved: