MongoDb query condition on comparing 2 fields

前端 未结 4 806
面向向阳花
面向向阳花 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:44

    If your query consists only of the $where operator, you can pass in just the JavaScript expression:

    db.T.find("this.Grade1 > this.Grade2");
    

    For greater performance, run an aggregate operation that has a $redact pipeline to filter the documents which satisfy the given condition.

    The $redact pipeline incorporates the functionality of $project and $match to implement field level redaction where it will return all documents matching the condition using $$KEEP and removes from the pipeline results those that don't match using the $$PRUNE variable.


    Running the following aggregate operation filter the documents more efficiently than using $where for large collections as this uses a single pipeline and native MongoDB operators, rather than JavaScript evaluations with $where, which can slow down the query:

    db.T.aggregate([
        {
            "$redact": {
                "$cond": [
                    { "$gt": [ "$Grade1", "$Grade2" ] },
                    "$$KEEP",
                    "$$PRUNE"
                ]
            }
        }
    ])
    

    which is a more simplified version of incorporating the two pipelines $project and $match:

    db.T.aggregate([
        {
            "$project": {
                "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] },
                "Grade1": 1,
                "Grade2": 1,
                "OtherFields": 1,
                ...
            }
        },
        { "$match": { "isGrade1Greater": 1 } }
    ])
    

    With MongoDB 3.4 and newer:

    db.T.aggregate([
        {
            "$addFields": {
                "isGrade1Greater": { "$cmp": [ "$Grade1", "$Grade2" ] }
            }
        },
        { "$match": { "isGrade1Greater": 1 } }
    ])
    

提交回复
热议问题