gpt4 book ai didi

MongoDB:$all 为空数组...

转载 作者:可可西里 更新时间:2023-11-01 09:55:36 26 4
gpt4 key购买 nike

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

{"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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com