您好,我尝试通过_id对所有元素进行分组,在所有情况下都一样
db.movies.aggregate([
{
$project:{
_id:{
award:{$cond:[
{$and:[{awards:{$regex:/win/}}]}
]}
},
imdb:1
}
},
{
$group:{
highest_rating:{$max:'$imdb.rating'},
lowest_rating:{$min:'$imdb.rating'},
average_rating:{$avg:'$imdb.rating'},
deviation:{$stdDevPop:'$imdb.rating'}
}
}
])
但是响应是
{
"message" : "Unrecognized expression '$regex'",
"operationTime" : "Timestamp(1560994467, 1)",
"ok" : 0,
"code" : 168,
"codeName" : "InvalidPipelineOperator",
"$clusterTime" : {
"clusterTime" : "Timestamp(1560994467, 1)",
"signature" : {
"hash" : "++GYj/cVU+Xk2bYmDYAowZfrhWw=",
"keyId" : "6661714504839069697"
}
},
"name" : "MongoError"
} 我在做什么错了?
答案 0 :(得分:1)
您不能在$ cond中使用$ regex。吉拉(Jira)中有一个特定问题,您可以在这里查看:
https://jira.mongodb.org/browse/SERVER-8892
答案 1 :(得分:0)
对于发现此问题的人(例如我),此问题已在2019年5月(https://jira.mongodb.org/browse/SERVER-11947)中得到纠正,您应该改用$regexMatch
db.coll.aggregate([{
$project: {
region: {
$cond: {
if: {
$regexMatch: {
input: “$phoneNumber”,
regex: “^212.*$”,
}
}
then: "New York",
else: "Somewhere Else"
}
}
}
}])
答案 2 :(得分:-1)
在不允许的$ regex组中,我将查询从$ group内的$ regex更改为$ match
db.movies.aggregate([
{
$match: {
$and: [
{ awards: { $exists: true } },
{ awards: { $regex: /Won/ } },
{
$or: [
{ awards: { $regex: /Oscar/ } },
{ awards: { $regex: /Oscars/ } }
]
}
]
}
},
{
$addFields: {
exists: 1,
}
},
{
$group: {
_id: "$exists",
highest_rating: { $max: '$imdb.rating' },
lowest_rating: { $min: '$imdb.rating' },
average_rating: { $avg: '$imdb.rating' },
deviation: { $stdDevPop: '$imdb.rating' }
}
}
])