Arek S
Arek S

Reputation: 4699

mongodb findAll with 2 parameters equal to each other

How do I translate this sql query to mongodb

Select * From Users Where type = "S" and registration_token = username;

I've tried this

$users = User::model()->findAll(array(
  "type" => "S",
  "registration_token" => "username"
));

but no joy...

Upvotes: 0

Views: 56

Answers (1)

mnemosyn
mnemosyn

Reputation: 46291

This is a relational query, so please keep in mind that MongoDB isn't geared towards this kind of operation like SQL is. This type of query will usually be significantly slower than in an SQL database. I'd also consider this type of 'meta-logic' bad design, because the fact that two seemingly independent values match shouldn't mean anything.

That said, you still have two options. You can use the JavaScript-based $where:

db.coll.find({$and : [ 
 {"type" : "S"}, 
 {"$where": function() { return this.registration_token === this.username; } }]})

However, this approach is slow because it needs to fire up JavaScript for each object it finds (i.e. for all those with type == 'S'). It might also have security implications if any of the data in the $where comes from the end user.

Alternatively, you can use the aggregation pipeline:

> db.coll.aggregate([{ "$project": { 
     "username": "$username", 
     "type": "$type", 
     "registration_token" : "$registration_token",
     "match": { "$eq": ["$username","$registration_token"]} }},
  { "$match": { "match": true } } ])

Upvotes: 1

Related Questions