mongoidmongodb-querymongoid4

MongoDB select documents based on multiple fields


Let's say we have the following documents in a collection:

{
    "_id" : ObjectId("55aa9d35dccf57b64d34f448"),
    "a" : 1,
    "b" : 7,
    "c" : 0
}

{
    "_id" : ObjectId("55aa9d64dccf57b64d34f449"),
    "a" : 2,
    "b" : 8,
    "c" : 1
}

{
    "_id" : ObjectId("55aa9d6bdccf57b64d34f44a"),
    "a" : 2,
    "b" : 7,
    "c" : 0
}

I want to get all documents where (a = 1 and b = 7) or (a = 2 and b = 8). The query will always be only on fields a and b, but there are going to be maybe ten thousand of possible a and b pairs (combinations).

Is there a way to do this kind of a query using $in operator?

If not, what would be the best way to do it?


Solution

  • The underlying MongoDB query you're trying to build is:

    $or: [
        { a: 1, b: 7 },
        { a: 2, b: 8 }
    ]
    

    That translates directly to:

    Model.where(:$or => [
        { :a => 1, :b => 7 },
        { :a => 2, :b => 8 }
    ])
    

    or you could use the or method:

    Model.or(
        { :a => 1, :b => 7 },
        { :a => 2, :b => 8 }
    )
    

    You don't need $in here, you'd use $in to see if a single field is equal to any of an array's elements. For example, these are equivalent:

    where(:$or => [ { :a => 1 }, { :a => 2 } ])
    where(:a => { :$in => [ 1, 2 ] })
    where(:a.in => [ 1, 2 ]) # a short form of :a => { :$in => ... }
    

    So $in is a special case shortcut for certain $ors.