mongoid .limit does not work in mongoid 3.1.x

前端 未结 3 1611
我在风中等你
我在风中等你 2021-02-19 18:17

i tried something like this in rails with mongoid 3.1.0 and lastest 3.1.3. .limit does not work. below it should return 1 row but it returns all (4)

code:



        
相关标签:
3条回答
  • 2021-02-19 19:07

    As suggested in the official Mongoid answer, we should be using Gallery.limit(1).count(true)

    0 讨论(0)
  • 2021-02-19 19:10

    For Mongoid 5 the parameter of CollectionView#count changed :

        # Get a count of matching documents in the collection.
        #
        # @example Get the number of documents in the collection.
        #   collection_view.count
        #
        # @param [ Hash ] options Options for the count command.
        #
        # @option options :skip [ Integer ] The number of documents to skip.
        # @option options :hint [ Hash ] Override default index selection and force
        #   MongoDB to use a specific index for the query.
        # @option options :limit [ Integer ] Max number of docs to return.
        # @option options :max_time_ms [ Integer ] The maximum amount of time to allow the
        #   command to run.
        #
        # @return [ Integer ] The document count.
        #
        # @since 2.0.0
    

    So you can do something like

    collection.count(limit: 1) # => 1
    
    0 讨论(0)
  • 2021-02-19 19:10

    The limit command works fine, but for some reason count ignores the limit. If you cast it to an array you'll see that the limit is working.

    Array(Gallery.limit(1)).length  # this gives 1
    

    Also, if you actually iterate through the objects you'll see that the limit is working.

    0 讨论(0)
提交回复
热议问题