How to return documents in which two fields have the same value

Is it possible to find only those documents in collections with the same value in two specified fields?

{
    _id:    'fewSFDewvfG20df', 
    start:  10,
    end:    10
}

As used herein startand endhave the same value, the document is selected.

I think of something like ...

Collection.find({ start: { $eq: end } })

... which will not work, as it endshould be a value.

+4
source share
2 answers

You have two options. The first is to use an operator $where.

Collection.find( { $where: "this.start === this.end" } )

The second option is to use the aggregation structure and the operator $redact.

Collection.aggregate([
    { "$redact": { 
        "$cond": [
            { "$eq": [ "$start", "$end" ] },
            "$$KEEP",
            "$$PRUNE"
        ]
    }}
])

Which one is better?

$where JavaScript , $where . . considerations. $, BSON JavaScript $where, . , , . , .

$redact, $where, , , $redact, MongoDB. , $match.

$where , . , $where, . , .

+5

, ,

Collection.find("this.start == this.end");
0

All Articles