gpt4 book ai didi

go - 如何在 go 中编写这些 mongo 代码

转载 作者:IT王子 更新时间:2023-10-29 01:52:39 26 4
gpt4 key购买 nike

My mongo File is here

 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"]
}
}
}
}
}
])

I try this one to write in go

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",],},}
},

},
},
}

But it show this on err syntax error: unexpected comma, expecting ]

请帮帮我。

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]",
},
},
},

},
},
}

This time compile successfully but after running the go file send me this err msg 2016/05/11 11:04:17 $expressions are not allowed at the top-level of $project exit status 1

最佳答案

您的代码中有两个错误:

1。 bson.M 中的数组

bson.M["$$ans.status","Active",] 会给你这样的错误 Type bson.M is not an expression,因为在这种情况下,您不需要键值对,字符串数组是更可取的情况。

尝试:

[]string{"$$ans.status","Active",}

2。逗号

根据 https://golang.org/doc/effective_go.html :

the lexer always inserts a semicolon after the token. This could be summarized as, “if the newline comes after a token that could end a statement, insert a semicolon”.

如果你没有在后面附加一个逗号,词法分析器会为你插入一个;,这将导致你当前的问题。

"$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 is not allowed at the top-level of $project,请注意mongodb中的聚合只接受数组,可以引用这个链接https://docs.mongodb.com/v3.0/reference/operator/aggregation/ :

db.collection.aggregate( [ { <stage> }, ... ] )

关于go - 如何在 go 中编写这些 mongo 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37153518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com