Search code examples
mongodbmorphia

Morphia. How to clone query with different collection(kind)


The problem is about searching by query in different collections.

There is a method in AdvancedDatastore interface:

<T> Query<T> createQuery(String kind, Class<T> clazz, DBObject q);

But its only create query with given baseQuery and I need full clone of Query but with different DBCollection field. Any suggestions?

Here is my method to convert query:

public Query<Vacancy> convertQuery(Query<T> query) {
        QueryImpl<T> queryImpl = (QueryImpl<T>) query;
        DBObject dbO = queryImpl.getQueryObject();
        Query<T> our_query = ((AdvancedDatastore)this.getDatastore()).createQuery("AnotherCollectionName", T.class, dbO);           
        return our_query;
    }

Update

Works fine with reflection, but I dont like this dirty way because of perfomance.


Solution

  • That looks like a good solution for now. You cannot change the underlying collection/kind once a query is created -- it is immutable.

    If you want this functionality one would need to implement a deep clone operator for the Query/QueryImpl or request that be done in morphia.