[cbmongodb-3.2.1]: How to specify OR conditions

Hi Jon,

I know how to specify AND conditions using where() from cbmongodb.

`
// Specify AND Conditions
// db.inventory.find( { type: ‘food’, price: { $lt: 9.95 } } )

result =
this.reset()
.where(“type”, “food”)
.where(“price”, “<”, 9.95)
.find();
`

How about OR conditions like below?

// Specify OR Conditions // db.inventory.find( // { // $or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ] // } // )

Another question, if I have dynamic conditions in a query, how to build such query? Should I use query()? If so, do you have any example how to use it?

Thank you.

Hi,

Its really simple, using orm criteria. I would suggest to read this doc

http://wiki.coldbox.org/wiki/ORM:CriteriaBuilder.cfm

The most recent version of CBMongoDB allows you to pass a direct Mongo query struct as the first argument in where().

So you can just do this:

result =
  this.reset()
  .where(
    {  
        "$or": [  
            {  
                "qty": { "$gt": 100 }  
            },  
            {  
                "price": { "$lt": 9.95 }  
            }  
        ]
    })
  .find();

You can also use the where() method’s assumed equality to do the following:

result =
    this.reset()
    .where("$or",[{"qty": { "$gt": 100 } }, { "price": { "$lt": 9.95 } } ])
    .find();

If you want to build it dynamically, you can also directly use theget_criteria() accessor to append conditions:

result =
    this.reset()
    .where("$or",[{"qty": { "$gt": 100 } }])
     
if(someCondition){
    arrayAppend(this.get_criteria()["$or"],{ "price": { "$lt": 9.95 } } );
}

return this.find();  

That said, I’ll add a tracker issue to put some kind of or() criteria builder in place that makes it easier to assemble them dynamically.

Thanks,

Jon

@AP Here you go: Implement an orWhere() function - Pivotal Tracker

Look for that functionality sometime in the next patch or two. :slight_smile:

Awesome…! Thanks so much for the answer.

No problem. BTW, your query was using find() which will only return a single result (and won’t throw an error like Hibernate does if it finds more than one result).

You’ll want to use findAll() for multiple results.