Khalid Bajwa
Khalid Bajwa

Reputation: 173

Mongoose query which compares field values

Say i have the following Scheme

TestSchema{
 val1:Number,
 val2:Number}

Would it be possible to write a query where all the results returned are where val1=val2 ?

If so , is there a way to use it when doing a populate ? (Perhaps inside the match field in the opts object ?)

Upvotes: 2

Views: 3146

Answers (3)

JohnnyHK
JohnnyHK

Reputation: 311835

You can do this with aggregate:

Test.aggregate([
    // Add a field to each doc that indicates if the two fields match
    {$project: {
        val1: 1,
        val2: 2,
        isMatch: {$eq: ['$val1', '$val2']}
    }},
    // Filter to just those docs where they match
    {$match: {isMatch: true}},
    // Remove isMatch to get back the original doc
    {$project: {
        val1: 1,
        val2: 1
    }}
], callback);

You can't do this to compare fields in populated results, only the queried collection.

This should be faster than using $where.

Upvotes: 1

Zlatko
Zlatko

Reputation: 19569

You can do this with $where operator.

TestModel.find({
    $where: 'this.val1 <= this.val2'
}).
exec(function(err, results) {
    // results here
});

You can alternatively pass a function to $where to work with results.

As Chris has said, this is an expensive operation, so test how it works first before deploying to production.

Upvotes: 1

Chris Cullins
Chris Cullins

Reputation: 101

I think what you want is the $where operator. Using that you could at least return the elements where those fields match.

Example: db.myCollection.find( "this.val2 == this.val2" );

I'm not in a place to be able to test this right now, so you may have to play with it a bit, but that should get you started.

I also should mention, there is a significant performance hit when using $where operations, so use cautiously.

Upvotes: 1

Related Questions