开发者

How do you write "(A OR B) AND (A OR C)" queries with Mongoid?

I need to write a MongoDB query of the form "A OR B OR (C AND D)" to return some records. We are using Mongoid for data access to our models.

I expanded that query to "(A OR B OR C) AND (A OR B OR D)" and was hoping that using Mongoid's Criteria method any_of like this: Model.any_of(A, B, C).any_of(A, B, D) would accomplish what I want, but that is expanded as "A OR B OR C OR A OR B OR D" before being sent to the database.

Is there a way to build this query, or do I have to build one query to d开发者_如何学运维o A OR B and another to do C AND D and take the union of them?


(Edit: I just noticed this question is 3 years old. I have no idea why it just showed up.)

You want something like this:

Model.any_of(a, b, c)

Where a, b, and c are selector documents (which, remember, are ANDed with multiple clauses).

For example, if your queries are:

{a: 1}
{b: 1}
{c: 1, d: 1}

Then you would use:

Model.any_of( {a: 1}, {b: 1}, {c: 1, d: 1} )

This would generate a query like:

models.find({$or: [{a: 1}, {b: 1}, {c: 1, d: 1}]})


Check this link, hope it might help you -

http://mongoid.org/docs/querying/

Probably if possible, you can combine ".any_in" and ".and" and check out.


It looks like this is a bug in mongo, but I'm having a tough time figuring out where mongo issues are reported / tracked.

> db.things.insert({x : 1, y: 2});
> db.things.insert({x : 2, y: 3});
> db.things.insert({x : 3, y: 4});
> db.things.find( { $or : [{x:1,x:2}], $or : [{y:1,y:2}] });
{ ..., "x" : 1, "y" : 2 }
{ ..., "x" : 2, "y" : 3 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜