mongodb query subset of an array

时光毁灭记忆、已成空白 提交于 2019-12-03 14:29:48

问题


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

For example:

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

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

EDIT: something like:

db.article.find({'_keywords': {$contains: array}})

回答1:


Use the $all operator:

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

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




回答2:


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"



回答3:


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



来源:https://stackoverflow.com/questions/12223465/mongodb-query-subset-of-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!