Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongoid query collection where two columns are equal to each other

I'm using Mongoid to connect to mongodb and need help with a query.

I have a Parent model where each parent and child has a name.

Class Parent
  field: :name
  field: :child_name
end

I could break the child out into another model and/or embed it, but my DB needs are simple. I want to query all the documents where the child name is the same as the parent name. (e.g. Father is Jeff and son is also Jeff).

Tried the following, but it doesn't work.

  parent = Parent.where(name: :child_name)

Not sure how to do it with Mongoid. Any help is much appreciated

like image 943
Jeff Locke Avatar asked Aug 30 '13 11:08

Jeff Locke


1 Answers

If you provide a string to Mongoid's where(), it assumes you're using JavaScript, and triggers MongoDB's native $where, which is what you need:

Parent.where("this.name == this.child_name")

like image 107
tkrajcar Avatar answered Oct 28 '22 11:10

tkrajcar