mongodb - ODM 查询生成器 : Is there an "inverse in" operator, 或等效操作?

标签 mongodb symfony odm

在我的 synfony 2 项目中,我使用查询生成器过滤搜索结果。在我的 MongoDB 中,我在数组中有一些值。

Query Bulider具有“in”运算符,允许查询等于数组中许多值之一的值。我想执行相反的操作,即给定一个值,查询数据库中包含数组的条目,该数组包含我的值。

例如,假设我的 MongoDB 中有此条目:

{
  "_id": 123,
  "name": "John",
  "countries_visited":
  [
    "Australia"
    "Bulgaria",
    "Canada"
  ]
}

我想在我的数据库中查询访问过“加拿大”的人。现在,我正在使用 where 属性,如下所示,但我正在寻找更好的方法来执行此操作。

        $qb->field('countries_visited')->where("function(){
            return this.indexOf(".$countryName.") > -1
        }");

编辑: innotIn 运算符接收一个数组作为参数,并将其与 MongoDB 中的单个值进行比较。我需要提供一个参数并将其应用于 MongoDB 中的数组字段,因此是“inverse in”。我想如果有这样的事情,我需要一个 contains 运算符。

最佳答案

有趣的是,MongoDB 会自动处理这个问题。如果针对数组字段查询单个值,Mongo 会假设您希望检查数组是否包含该值。

取自 docs :

Match an Array Element

Equality matches can specify a single element in the array to match. These specifications match if the array contains at least one element with the specified value.

所以你应该能够做到

$users = $dm->getRepository('User')->findOneBy([
    'countries_visited' => 'Canada'
]);

$qb->field('countries_visited')->equals('Canada');

关于mongodb - ODM 查询生成器 : Is there an "inverse in" operator, 或等效操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26237655/

相关文章:

javascript - 仅当 mongoDB Node JS 上存在集合时才显示给客户端

javascript - MongoDB .find 在 shell 中有效,但在 js 中无效

Symfony RememberMe token_provider

node.js - Redis 的 Nodejs 对象文档模型

javascript - 将javascript普通对象转换为模型类实例

mongodb - 计算符合给定条件的子文档

node.js - 从多个集合 MongoDB 创建 View

php - 在 symfony4 中为 redis 设置无键前缀

php - Symfony2 Controller 中未捕获 Swiftmailer 异常