我的mongo文件在这里
db.aaa.aggregate([{
$match : {
status : "Active"
}
}, {
$project : {
_id : 1,
title : 1,
postdatetime : 1,
status : 1,
answer : {
$filter : {
input : "$answer",
as : "answe",
cond : {
$eq : ["$$answe.status", "Active"]
}
}
}
}
}
])
我试着写一下
o2 := bson.M{
"$project":bson.M{
"$answer":bson.M{
"_id":1,"title":1,"postdatetime":1,"status":1,"answer":bson.M{
"$filter":bson.M{"input":"$answer","as":"ans","cond":bson.M{"$eq":bson.M["$$ans.status","Active",],},}
},
},
},
}
但它显示错误 语法错误:意外逗号,期待]
请帮帮我。
After the answer i try this one
o2: = bson.M {
"$project": bson.M {
"$answer": bson.M {
"_id": 1,
"title": 1,
"revision": 1,
"bgimageurl": 1,
"author": 1,
"postdatetime": 1,
"status": 1,
"qatags": 1,
"followers": 1,
"qaviews": 1,
"answer": bson.M {
"$filter": bson.M {
"input": "$answer",
"as": "ans",
"cond": bson.M {
"$eq": "[$$ans.status][,Active]",
},
},
},
},
},
}
这次编译成功但是在运行go文件之后发送给我这个错误信息 2016/05/11 11:04:17 $表达式不允许在$ project的顶层 退出状态1
答案 0 :(得分:3)
您的代码中有两个错误:
bson.M["$$ans.status","Active",]
会给出Type bson.M is not an expression
之类的错误,因为在这种情况下你不需要键值对,所以字符串数组会是一个更好的例子。
尝试:
[]string{"$$ans.status","Active",}
根据https://golang.org/doc/effective_go.html:
词法分析器总是在令牌后插入分号。这可以概括为“如果新行出现在可以结束语句的标记之后,则插入分号”。
如果您在}
之后没有添加逗号,则词法分析器会为您插入;
,这将导致您当前的问题。
"$filter":bson.M{"input":"$answer","as":"ans","cond":bson.M{"$eq":bson.M{"$$ans.status","Active",},},} // should add a comma at the end of the line
修改后:
"$filter":bson.M{"input":"$answer","as":"ans","cond":bson.M{"$eq":[]string{"$$ans.status","Active",},},},
对于您的第二个问题$expressions are not allowed at the top-level of $project
,请注意mongodb
中的汇总仅接受array
,您可以参考此链接https://docs.mongodb.com/v3.0/reference/operator/aggregation/:
db.collection.aggregate( [ { <stage> }, ... ] )
答案 1 :(得分:2)
完成所有这一切后,
工作
mysql> show processlist;
+------+-----------------+----------------------+-------------+---------+----------+------------------------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+------+-----------------+----------------------+-------------+---------+----------+------------------------+------------------+
| 1 | event_scheduler | localhost | NULL | Daemon | 13200075 | Waiting on empty queue | NULL |
| 4212 | root | localhost | NULL | Query | 0 | init | show processlist |
| 4214 | root | xxx.xx.xxx.xxx:50197 | testmysqldb | Sleep | 1 | | NULL |
| 4215 | root | xxx.xx.xxx.xxx:50198 | testmysqldb | Sleep | 3 | | NULL |
+------+-----------------+----------------------+-------------+---------+----------+------------------------+------------------+