MongoDb query condition on comparing 2 fields

前端 未结 4 799
面向向阳花
面向向阳花 2020-11-22 00:44

I have a collection T, with 2 fields: Grade1 and Grade2, and I want to select those with condition Grade1 > Grade2, ho

4条回答
  •  心在旅途
    2020-11-22 01:34

    In case performance is more important than readability and as long as your condition consists of simple arithmetic operations, you can use aggregation pipeline. First, use $project to calculate the left hand side of the condition (take all fields to left hand side). Then use $match to compare with a constant and filter. This way you avoid javascript execution. Below is my test in python:

    import pymongo
    from random import randrange
    
    docs = [{'Grade1': randrange(10), 'Grade2': randrange(10)} for __ in range(100000)]
    
    coll = pymongo.MongoClient().test_db.grades
    coll.insert_many(docs)
    

    Using aggregate:

    %timeit -n1 -r1 list(coll.aggregate([
        {
            '$project': {
                'diff': {'$subtract': ['$Grade1', '$Grade2']},
                'Grade1': 1,
                'Grade2': 1
            }
        },
        {
            '$match': {'diff': {'$gt': 0}}
        }
    ]))
    

    1 loop, best of 1: 192 ms per loop

    Using find and $where:

    %timeit -n1 -r1 list(coll.find({'$where': 'this.Grade1 > this.Grade2'}))
    

    1 loop, best of 1: 4.54 s per loop

提交回复
热议问题