我如何查询mongo来查找包含另一个数组的TWO元素的数组
假设我在mongo中有以下文件:
{_id: 0, tags: ['first', 'second', 'third', fourth']}, {_id: 1, tags: ['fifth', 'seventh', 'first', second']}, {_id: 2, tags: ['eigth', 'awesometh', 'fancyth']}, {_id: 3, tags: ['fourth', 'fifteenth', 'something']},
我想从以下数组中find包含两个或两个以上的文档: ['first', 'second', third', 'fourth', 'fifteenth']
我到目前为止唯一的想法是用每个组合的子句生成I巨大的查询,如下所示:
{$or: [ {tags: {$in: ['first', 'second']}}, {tags: {$in: ['second', 'third']}}, {tags: {$in: ['first', 'third']}}, ...etc... ] }
这显然不是一个优雅的解决scheme。 有没有更好的办法?
您可以使用$setIntersection
来查找匹配的tags
,然后使用$size
来计算它们:
var tags = ['first', 'second', 'third', 'fourth', 'fifteenth']; db.test.aggregate([ // Project the original doc along with a count of the tag matches {$project: { _id: 0, matches: {$size: {$setIntersection: ['$tags', tags]}}, doc: '$$ROOT' }}, // Filter to just those docs with at least 2 matches {$match: {matches: {$gte: 2}}} ])
产量
{ "matches": 4, "doc": { "_id": 0, "tags": ["first", "second", "third", "fourth"] }} { "matches": 2, "doc": { "_id": 1, "tags": ["fifth", "seventh", "first", "second"] }} { "matches": 2, "doc": { "_id": 3, "tags": ["fourth", "fifteenth", "something"] }}
- Mongoose find()返回一个空文档
- 存储在MongoDB中的Node.jsdate对象为“1970-01-01T00:00:00.001Z”
- Mongodb / Couchdb而不是MySQL(从PHP切换到节点)
- OpenShift:ImportError:在NodeJs / Mongo盒式磁带上没有名为gyp:的模块
- 如何使用node.JS创build一个基于令牌的login机制?
- 使用Mongoose时出错'Object has no method xxx'
- 节点REST API图像呈现问题
- Mongoose保存在async.each中创build重复项
- meteordynamicMongoDB集合