在 MongoDB 中,我可以投影一个值是否有一个新字段的子字符串吗? [英] In MongoDB, can I project whether a value has a substring to a new field?

查看:49
本文介绍了在 MongoDB 中,我可以投影一个值是否有一个新字段的子字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MongoDB 中,我想根据某个字段是否具有某个子字符串来对我的文档进行分组.我试图将每个文档投影到一个布尔值,表示该字段是否具有该子字符串/匹配该模式,然后按该字段分组.

In MongoDB, I want to group my documents based on whether a certain field has a certain substring. I was trying to project each document to a boolean that says whether the field has that substring/matches that pattern, and then group by that field.

我该怎么做?

1) 我已经尝试将聚合管道作为

1) I have tried the aggregation pipeline as

db.aggregate([
   { 
      '$match': { 
          '$regex': '.*world'
      }
   }
])

但我收到一个错误:

pymongo.errors.OperationFailure: command SON([('aggregate', u'test'), ('pipeline', [{'$match': {'$regex': '.*world'}}])]) failed: exception: bad query: BadValue unknown top level operator: $regex

2) 我不想只选择与模式匹配的单词.我想选择每个文件.我想创建一个名为 'matched' 的字段,该字段表示该模式是否与每个元素匹配.

2) I am NOT trying to select only the words that match the pattern. I would like to select every document. I would like to make a field called 'matched' which says whether the pattern was matched for each element.

推荐答案

$regex 运算符需要出现在您匹配的字段之后:

The $regex operator needs to appear after the field that you are matching on:

db.aggregate([
  {
    "$match": { 
      "fieldName": {"$regex": ".*world"}
    }
  }
])

未知顶级运算符"消息意味着该运算符必须出现在适用于它的字段之后.

The "unknown top level operator" message means that the operator has to appear after the field to which it applies.

这篇关于在 MongoDB 中,我可以投影一个值是否有一个新字段的子字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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