A subset of the mongodb array requests

I have a _keywords field, which is an array of strings. I want to get documents from which _keywords are a super-set of requests array.

For instance:

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

I want to extract this entry when I request a subset of ['foo', 'foo1', 'foo2'], for example: ['foo'], ['foo1', 'foo2']

EDIT: something like:

 db.article.find({'_keywords': {$contains: array}}) 
+6
source share
3 answers

Use the $all operator:

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

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

+11
source

In MongoDb for an 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" 
+5
source

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

+1
source

Source: https://habr.com/ru/post/924321/


All Articles