MongoEngine/mongoengine

Compare two QuerySets Efficiently

Inventrohyder opened this issue · 1 comments

What is the most efficient way to compare two QuerySets?

  1. ==
  2. to_json()
  3. or this function
    from mongoengine import QuerySet
    
    def compare_querysets(query1: QuerySet, query2: QuerySet):
        # Check if the querysets have the same number of documents
        if query1.count() != query2.count():
            return False
    
        # Check if all documents in query1 exist in query2
        for doc in query1:
            if not query2.exists(doc):
                return False
    
        # If both checks pass, the querysets are considered equal
        return True
    
  4. something else?

This would be more for Stackoverflow than the projects issue tracker but if you are trying to assess if both querysets returns the exact same records, then probably the best is to compare


def compare_querysets(query1: QuerySet, query2: QuerySet):
    return set(query1.distinct("id")) == set(query2.distinct("id"))

This would load all id of both queries in memory but if you can afford it, this is probably the most efficient.

Hope this helps