MongoDB:$all 为空数组...

标签 mongodb find

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

{"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. 当 match 有值时,返回所有匹配这些值的文档(完成)
  2. 当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/

相关文章:

node.js - MongoDB断言错误 "ECONNREFUSED"

c++ - opencv c++ 找到轮廓的内接圆

linux - 递归查找并复制到其他目录

linux - 为什么在 find 命令中使用 dirname 会为每个匹配项提供点?

mysql - Cakephp 找到连接两列

jquery - 查找元素是否包含 x 但不包含 y (jQuery)

java - 通过 mongoDB Java 驱动获取 mongoStat

mongodb - mongorestore 在分片集群 v4.2.x 上失败 |错误 : "panic: close of closed channel"

mongodb - XML 与 MongoDB

database - 如何删除 MongoDB 中的所有数据库?