mongodb query subset of an array
Asked Answered
E

3

10

I have a field _keywords which is an array of strings. I want to get documents where _keywords is a super-set of the query array.

For example:

db.article.insert({'_keywords': ['foo', 'foo1', 'foo2']})

I want to retrieve this record when I query subset of ['foo', 'foo1', 'foo2'], eg: ['foo'] or ['foo1', 'foo2']

EDIT: something like:

db.article.find({'_keywords': {$contains: array}})
Evert answered 31/8, 2012 at 23:6 Comment(0)
E
13

Use the $all operator:

db.article.find( { _keywords: { $all: [ 'foo1', 'foo2' ] } } );

Source: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24all

Eric answered 31/8, 2012 at 23:18 Comment(2)
How to retrive documents where _keywords contains any item in the given query array. something like: db.article.find({_keywords: {$any: ['foo1', 'foo2']}}), which returns any documents with _keywords contains 'foo1' or 'foo2'Evert
As I can remember, in such case you can use $in, for example: db.article.find({_keywords: {$in: ['foo1', 'foo2']}}). Check if this is right.Eric
C
18

In MongoDb, for array field:

"$in:[...]" means "intersection" or "any element in",
"$all:[...]" means "subset" or "contain",
"$elemMatch:{...}" means "any element match"
"$not:{$elemMatch:{$nin:[...]}}" means "superset" or "in"
Cloudless answered 27/3, 2014 at 3:35 Comment(1)
Great breakdown into set theory! Helped me get my head around it since I needed the field to be a subset meaning the values passed in the query are the superset (the double negation query at the end).Infallible
E
13

Use the $all operator:

db.article.find( { _keywords: { $all: [ 'foo1', 'foo2' ] } } );

Source: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24all

Eric answered 31/8, 2012 at 23:18 Comment(2)
How to retrive documents where _keywords contains any item in the given query array. something like: db.article.find({_keywords: {$any: ['foo1', 'foo2']}}), which returns any documents with _keywords contains 'foo1' or 'foo2'Evert
As I can remember, in such case you can use $in, for example: db.article.find({_keywords: {$in: ['foo1', 'foo2']}}). Check if this is right.Eric
E
2

Short answer: $all operator.
To query documents with array with superset of ['foo1', 'foo2'], use:
db.article.find( { '_keywords': { $all: ['foo1', 'foo2'] } } );

Esau answered 31/8, 2012 at 23:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.