MongoDB仅按数组属性过滤(如果存在) [英] MongoDB filter by array property only if it exists

查看:345
本文介绍了MongoDB仅按数组属性过滤(如果存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库对象有一个名为tags的可选属性,它是一个字符串数组.我想编写一个查询,如果它们符合以下条件之一,则返回对象:

My database object has an optional property named tags which is a string array. I want to write a query that returns objects if they match one of these conditions:

  1. 他们没有tags属性.
  2. 它们具有标签属性,该属性至少在另一个称为queryTags
  3. 的数组中包含一项
  1. They don't have a tags property.
  2. They have a tags property that has at least one item included in another array called queryTags

通过阅读文档,我想到了以下内容,但它不起作用:

From reading the documentation I came up with the following but it doesn't work:

let query = {
    tags: { '$or': [{'$exists': false}, {'$in': queryTags}]}
}

推荐答案

$or是顶级运算符,因此您的查询必须是:

$or is a top-level operator, so your query needs to be:

let query = {
    '$or': [{tags: {'$exists': false}}, {tags: {'$in': queryTags}}]
}

这篇关于MongoDB仅按数组属性过滤(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆