hielsnoppe
hielsnoppe

Reputation: 2869

MongoDB $match by array subset

In a MongoDB storing objects the form of

{ array: ["a", "b", "c", ... ] }
{ array: ["a", "d", "f", ... ] }
...

I want to retrieve all objects having e.g. "b" or "d" as values in their array field. How can I do this? What I tried is

{ $match: { array: { $all: [ "b", "d" ] } } }

but this requires "b" and "d" to be present in order to match.

Upvotes: 2

Views: 892

Answers (1)

brianz
brianz

Reputation: 7418

You can use the $or operator with a simple query on the array field, or an $in operation as Sammaye points out below (which will be more performant):

http://docs.mongodb.org/manual/reference/operator/or/#op._S_or

> db.coll.insert({ array: ["a", "b", "c"] })
> db.coll.insert({ array: ["a", "d", "f"] })
>
> db.coll.find({ array : 'b' })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
>
> db.coll.find({ array : 'a' })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("51cc7ab481e227fe57ccb56a"), "array" : [ "a", "d", "f" ] }

$in:

> db.coll.find({ array : { $in : ['a', 'b'] } })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("51cc7ab481e227fe57ccb56a"), "array" : [ "a", "d", "f" ] }

> db.coll.find({ array : { $in : ['c', 'z'] } }) 
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }

$or:

> db.coll.find({ $or : [ { array  : 'a' }, { array : 'b' } ] })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }
{ "_id" : ObjectId("51cc7ab481e227fe57ccb56a"), "array" : [ "a", "d", "f" ] }
>
> db.coll.find({ $or : [ { array  : 'c' }, { array : 'z' } ] })
{ "_id" : ObjectId("51cc7aa881e227fe57ccb569"), "array" : [ "a", "b", "c" ] }

If you add an index on the array field these queries will be faster.

Upvotes: 4

Related Questions