markhorrocks
markhorrocks

Reputation: 1548

How to compare fields in Meteor find query

In a meteor find query how can I compare two fields? I want to do something like the following SQL query.

select * from games g where g.game_minutes > (minutes_since_midnight_now - g.game_duration)

In view of the answers below I did some experimenting along the way to comparing two fields:

this works:

      var nextGame = Games.findOne(
              {
               game_minutes: {$gt: minutesSinceMidnight},
               court_id: court,
               game_date: {$gt: yesterday}
              },
              {
               sort: {game_minutes: 1}
              }
              );

this does not work:

      var nextGame = Games.findOne(
              {
               $where: "this.game_minutes" > minutesSinceMidnight, 
               court_id: court,
               game_date: {$gt: yesterday}
              },
              {
               sort: {game_minutes: 1}
              }
              );

Ultimately I want something like this:

$where: "this.game_minutes" > (minutesSinceMidnight - "this.game_duration"), 

Upvotes: 2

Views: 705

Answers (2)

Johan Persson
Johan Persson

Reputation: 2055

Since you haven't specified why the following doesn't work...

var nextGame = Games.findOne(
          {
           $where: "this.game_minutes" > minutesSinceMidnight, 
           court_id: court,
           game_date: {$gt: yesterday}
          },
          {
           sort: {game_minutes: 1}
          }
          );

...I'm going to guess it is because Mongodb expects either a string or a function to the $where clause. I'm also guessing you have tried what Ayonix suggested in his comment, to use...

$where: "this.games_minutes > minutes_since_midnight_now - this.game_duration"

...and that this did not work. Without trying it myself, I'm thinking Mongodb has no way of evaluating what "minutes_since_midnigt_now" is when executing and parsing the $where string you passed it.

However, $where also seems to accept a full javascript function, so maybe this will work instead:

var nextGame = Games.findOne(
          {
           $where: function () { return this.game_minutes > minutesSinceMidnight - this.game_duration; },

           court_id: court,
           game_date: {$gt: yesterday}
          },
          {
           sort: {game_minutes: 1}
          }
          );

If this doesn't work, maybe you can disclose some more details as of what is happening when it "doesn't work"? Do you see an error? Doesn't it compile? Or does it simply not return anything at all?

Upvotes: 2

Ayonix
Ayonix

Reputation: 2002

games.find({game_minutes: {$gt: minutes_since_midnight_now - g.game_duration}});

As seen here: How to use $min mongo query in Meteor.js?

Update: To compare two attributes of a document you would have to use a games.find({$where: "this.game_minutes > minutes_since_midnight_now - this.game_duration"}) or similar.

Upvotes: 2

Related Questions