negate $elemmatch

3,870 views
Skip to first unread message

Dominik Gehl

unread,
Jun 15, 2011, 1:12:38 PM6/15/11
to mongodb-user
Hi,

I would like to find all documents for which no entry in an array
matches a specified $elemMatch.

I've tried (php syntax)

$result = $collection->find(
array(
'arrayField' => array(
'$not' => array(
'$elemMatch' => array(
'subField1' => 'value1',
'subField2' => 'value2'
)
)
)
)
);

But this doesn't seem to return the "right" documents. Any hints on
how I can properly negate the $elemMatch ?

Thanks,
Dominik

Kyle Banker

unread,
Jun 15, 2011, 9:38:28 PM6/15/11
to mongodb-user
Can you provide a sample test case? This seems to work for me:

db.foo.save({a: [ {n: 1, r: 10}, {n: 2, r: 10}]})
db.foo.save({a: [ {n: 1, r: 20}, {n: 2, r: 10}]})
db.foo.save({a: [ {n: 1, r: 30}, {n: 2, r: 10}]})

db.foo.find({a: { $not: {$elemMatch: {n: 1, r: 10 } } } })

Returns:
{ "_id" : ObjectId("4df95e583247c06301302ec5"), "a" : [ { "n" : 1,
"r" : 20 }, { "n" : 2, "r" : 10 } ] }
{ "_id" : ObjectId("4df95e593247c06301302ec6"), "a" : [ { "n" : 1,
"r" : 30 }, { "n" : 2, "r" : 10 } ] }

That's correct.

Dominik Gehl

unread,
Jun 16, 2011, 9:10:04 AM6/16/11
to mongodb-user
You are right, it's working !

I must have had some typo somewhere while testing this ...

Thanks,
Dominik
Reply all
Reply to author
Forward
0 new messages