Uploaded image for project: 'Mongoid'
  1. Mongoid
  2. MONGOID-4773

Aggregation to Mongoid::Criteria

    • Type: Icon: Improvement Improvement
    • Resolution: Duplicate
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 5.4.0
    • Component/s: None
    • None
    • Environment:
      rails, mongoid

      Given I have a collection User and a collection Calendar and a Calendar belongs_to User and I want to sort calendars by the user name. When I use the aggregation framework:

      collection = Calendar.collection.aggregate([
        {'$match' => { _id:

      { '$in' => @selectedCalendars.pluck(:id) }

      }},
        {'$lookup' => { from: 'users', localField: 'owner_id', foreignField: '_id', as: 'owners' }},
        {'$unwind' => '$owners' },
        {'$sort' =>

      { 'owners.last_name' => -1, 'owners.first_name' => -1 }

      },
        {'$group' => { _id: nil, ids:

      { '$addToSet' => '$_id' }

      } },
        {'$project' =>

      { _id: 0 }

      }
      ])

      I get back a Mongo::Collection::View::Aggregation instance. But what I need back is a Mongoid::Criteria, because I need to be able to chain additiona query methods like where, or, and even paginate. This data needs to be paginated with the pagination library I am using which is expecting a criteria.

      You might say well you have no other option but to get the ids from $project and wrap that in an '$in' query, as such:

      > collection.entries
      => [{"ids"=>[BSON::ObjectId('5d8546593ed149344bfa5667'), BSON::ObjectId('5d8546363ed14934356506ee'), BSON::ObjectId('5d8546593ed149344bfa5665')]}]
      > Calendar.in(_id: collection[0]['ids'])

      While this will give me a Mongoid::Criteria, it no longer preserves the sort order I had created in the aggregation (the call to in() ignores the order of the ids). So now I don't know how this issue could be resolved. I need to be able to preserve that expensive sort order. What is one to do without this feature?

       

       

            Assignee:
            oleg.pudeyev@mongodb.com Oleg Pudeyev (Inactive)
            Reporter:
            danvig2 John Merlino
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: