问题
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