使用$ regex在MongoDb中查询多个字段

我正在关注Angular Meteor教程,它具有以下代码:

import { Meteor } from 'meteor/meteor';
import { Counts } from 'meteor/tmeasday:publish-counts';

import { Parties } from './collection';

if (Meteor.isServer) {
  Meteor.publish('parties', function(options, searchString) {
    const selector = {
      $or: [{
        // the public parties
        $and: [{
          public: true
        }, {
          public: {
            $exists: true
          }
        }]
      }, {
        // when logged in user is the owner
        $and: [{
          owner: this.userId
        }, {
          owner: {
            $exists: true
          }
        }]
      }]
    };

    if (typeof searchString === 'string' && searchString.length) {
      selector.name = {
        $regex: `.*${searchString}.*`,
        $options : 'i'
      };
    }

    Counts.publish(this, 'numberOfParties', Parties.find(selector), {
      noReady: true
    });

    return Parties.find(selector, options);
  });
}

我正在尝试修改selector.name以包括描述字段。我已经检查了添加选择器。描述,但是什么也没做。在将正则表达式与文档的任一字段匹配时,是否可以修改选择器以包括搜索多个字段?

米歇尔·弗洛伊德(Michel Floyd)

“两个”都可能意味着$or:-如果您仅添加description到对象,则最终会得到一个$and:

在获得名称和描述标准之前,您的选择器将是:

let selector =
  { $or:
    [
      { $and: [ { public: true }, { public: { $exists: true } } ] },
      { $and: [ { owner: this.userId }, { owner: { $exists: true } }] }
    ]
  };

(请注意,let而不是const

为此,您想$and:附加一秒钟$or:

if (typeof searchString === 'string' && searchString.length) {
  selector = { $and:
    [ 
      selector,
      { $or:
        [
          { name: { $regex: `.*${searchString}.*`, $options : 'i' }},
          { description: { $regex: `.*${searchString}.*`, $options : 'i' }},
        ]
      }
    ]
  };
}

最后,您应该具有一个类似于以下内容的对象:

{ $and:
  [ 
    { $or: [ public criteria, owner criteria ] },
    { $or: [ name regex, description regex ] }
  ]
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

尝试在Mongodb中同时使用$ regex查找多个字段

在MongoDB中的多个字段上使用$ in

使用MongoDB从单独集合中的文档聚合多个字段

如何使用Perl在mongodb中按多个字段排序?

使用MeteorJS在MongoDB中搜索多个字段

如何使用SelectTokens查询多个字段?

使用mongodb查询单个字段

如何使用查询语法在Lucene中跨多个字段进行搜索?

使用一个查询更新一列中的多个字段

如何使用查询对象比较Spring Data MongoDB中的2个字段

使用 VB.net 和 MONGODB 更新文档中的多个字段(列)

MongoDb-如何使用Java对集合中的多个字段进行排序和搜索

使用mongodb中的聚合获取包含多个字段的最大值的对象

如何使用 MongoDB 中的单个管道计算多个字段的频率?

SQL如何使用单个查询替换同一表的单个字段中的多个字符

需要对使用mongodb聚合查询从另一个集合连接的多个字段进行不同的计数

如何使用MySQL查询顺序连接多个字段?

MySQL在触发之前,使用查询设置多个字段

使用一个更新查询设置多个字段

如何在 django-filter 中的多个字段上使用一个查找字段过滤查询集

选择查询以在Solr中的多个字段中使用2个或多个不带双引号的单词进行搜索

MongoDB使用$ or查找具有多个查询字段的查询

使用mongodb聚合的多个字段的不同计数

MongoDB:在多个字段或数组上使用索引

使用多个字段的mongodb查找不起作用

使用 Mongoose 在 MongoDB 中查询多个属性

使用 Lodash 在 Nodejs 中按多个字段分组

如何使用elasticsearch在多个字段中搜索?

如何使用搜索在Swift中搜索多个字段?