我正在对包含此类文档的集合运行查询。
{"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}});
现在我需要做以下事情:
- 当 match 有值时,返回所有匹配这些值的文档(完成)
- 当match为空[]时,返回所有文档。
在单个查询中执行此操作的最有效方法是什么?
提前致谢
D
最佳答案
我建议您在应用层添加条件,并使在服务器上执行的query
非常简单。
- 如果
match
数组有一个或多个元素,添加一个查询字段到 您的查询condition
,否则执行空条件 将所有文件归还给您。
片段:
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.
关于MongoDB:$all 为空数组...,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29856239/