In MongoDB, can I project whether a value has a substring to a new field?

梦想的初衷 提交于 2019-12-25 03:21:48

问题


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.

How can I do this?

Edit:

1) I have tried the aggregation pipeline as

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

But I get an error:

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

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.


回答1:


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.



来源:https://stackoverflow.com/questions/25824973/in-mongodb-can-i-project-whether-a-value-has-a-substring-to-a-new-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!