Вопрос

I have pipeline many level in, Now I would like to compare two fields like follow:

db.collection.aggregate({ ...},
{$match:{firstfield:{$gte:"$secondfield"}}})

How to write this query?

Это было полезно?

Решение

Close but the actual invocation is slightly different:

db.collection.aggregate([
    { "$project": {
        "firstfield": 1,
        "secondfield": 1,
        "difference": { "$gte": [ "$firstfield", "$secondfield" ] }
    }},
    { "$match": { "difference": true } }
])

So a bit different to the $match invocation, the $project ( or possibly $group ) form allow for a true|false value to be returned on the field comparison.

This allows you to filter with the $match phase later in the pipeline in order to "include|exclude" results based on the logical condition that was projected.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top