Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get model with atleast one relation object in mongoid

I have a Person object which has_many companies. I would like to get the person with atleast one company. What I can get right now is

Person.where(:company_ids.size => 1)

This will return all the person with one company . But I need something like

Person.where(:company_ids.size.gte => 1)

But it seems , this does not work.

Solution :

sorry for all the trouble, but found out that with previously created objects , I didn't have company_ids ... since I had only added that later. I can get the count with following :

Person.where(:company_ids.exists => true).and("this.company_ids.length > 0") 

Thanks everyone for helping out.

like image 755
Prabesh Shrestha Avatar asked Dec 22 '22 06:12

Prabesh Shrestha


1 Answers

I assume company_ids a array field in person document

I am afraid there is no way of specifying conditions in size. But there is a workaround using javascript $where expression

 db.person.find({$where: '(this.company_ids.length > 0)'})

am not sure about how to pass this expression in mongoid.

EDIT

yeah you can do this with mongoid too

Person.where("$where" =>  'this.company_ids.length >0;' )
like image 161
RameshVel Avatar answered Jan 14 '23 21:01

RameshVel