MongoDB: $all 为空数组...

MongoDB: $all with empty array...

我正在 运行 查询包含此类文档的集合。

{"name": "Daniel", "tags": ["person", "owner", "father"]},
{"name": "Jane", "tags": ["person", "owner", "mother"]},
{"name": "Jimmy", "tags": ["person", "owner", "son"]}

现在,如果我想找到与标签 person AND owner 匹配的所有文档,我会这样做

var match = ['person', 'owner'];
model.find({'tags': {$all: match}});

现在我需要做以下事情:

  1. 当匹配有值时,return 所有匹配这些值的文档(已完成)
  2. 当匹配为空时[ ],return 所有文件。

在单个查询中执行此操作的最有效方法是什么?

提前致谢,

D

我建议您在应用层添加条件,并使在服务器上执行的 query 非常简单。

  • 如果match数组有一个或多个元素,添加一个查询字段到 您的查询 condition,否则执行空条件 return你所有的文件。

片段:

var match = ['person', 'owner'];
var condition = {};
if(match.length > 0){
   condition["tags"] = {$all:match};
}
db.model.find(condition);

话虽如此,使用 $all 运算符,不可能在单个查询中同时满足这两个条件。

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.