Domanda

I was wondering if it was possible to use the "in" operator as you can from the mongo shell, using the perl MongoDB::Collection module. I have tried a number of things, but haven't quite got the result I am expecting. I've check the docs and other posts on stackoverflow but can't seem to find anything specifically about this, unless I am overlooking something.

http://docs.mongodb.org/manual/reference/operator/query/in/

The count query I am running via the mongo shell is

mongo:PRIMARY> db.getCollection("Results").count( { TestClass : "TestClass", TestMethod : { $in: ["method1" , "method2", "method3"] } })
181605

I have tried this a few different ways passing the list as an array or hash-refs or pre-building a string...

my $count = $mongo->{collection}->count({
                            'TimeStamp'     => { '$gt' => $ft, '$lt' => $tt },
                            'TestClass'     => $TestClass,
                            'TestMethod'    => { '$in' => [$whitelist->methods] },
                            'Result'        => $result
                    });

Where Dumping $whitelist->methods is

$VAR1 = {
      'method1' => 1,
      'method2' => 1,
      'method3' => 1
    };

I've looked high and low for an answer, does anyone know if the driver is currently capable of using the $in operator like this? Looping through the returned methods from a previous query and adding up the results will require more code.

The only other stack overflow post I have seen about the $in operator was this $in mongoDB operator with _id in perl recommending using http://api.mongodb.org/perl/current/MongoDB/OID.html but don't think that is relevant in my example as looks more to do with ID's.

Any help or discussion would be greatly appreciated.

È stato utile?

Soluzione

The problem is that $in clause expects its value to be an array reference, but you supply a hashref (as Dumper's output shows) into it. The easiest way to turn the latter into the former is to apply keys function:

# ...
'TestMethod'    => { '$in' => [keys %{$whitelist->methods}] }

... or just [keys $whitelist->methods], if you're using Perl 5.14+, as ...

starting with Perl 5.14, keys can take a scalar EXPR, which must contain a reference to an unblessed hash or array

.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top