英文:
forming structure to read bson object with composite key
问题
我有一个聚合查询(MongoDB,使用mgo库),它通过一个复合键对文档进行分组。我想将这个聚合的结果添加到另一个集合中(我已经使用了聚合的out阶段,它显示了正确的结果,但是每次运行查询时都会覆盖记录)。
分组阶段的代码片段:基本上,我是按照由a、b和c组成的键进行分组。
"$group": bson.M{
"_id": bson.M{
"a": "$a",
"b": "$b",
"c": "$c",
},
x: "x",
y: "y",
// 其他字段
}
我已经使用out阶段测试了聚合/分组等操作,并得到了预期的结果。
要添加到另一个集合中,我想将每个bson对象作为结构体读取,然后插入到另一个集合中。问题是如何为复合键定义对象。
例如:
type test struct {
Id string `bson:"_id"` // <---- 如何定义我想在新集合中用作键的复合键
X string `bson:"x"`
Y string `bson:"y"`
}
我希望我的问题清楚明了,如果需要更多信息来回答这个问题,我可以补充。
英文:
I have an aggregation query (MongoDB, using mgo library), which groups the documents by a composite key. I want to add the result of this aggregation to another collection (I have use out stage of aggregation The result of this aggregation, which shows correct results but I cannot use out since it overwrites records every time the query is run).
snippet of group stage: basically I am grouping by a key which is composite, of a,b and c.
"$group": bson.M{
"_id": bson.M{
"a": "$a",
"b": "$b",
"c": "$c",
},
x: "x",
y: "y" ..etc
I have tested the aggregation / grouping etc with out stage and it gives expected result.
To add to another collection, I want to read each bson object as a struct and then insert into another collection. The problem is how to define the object for the composite key.
For example:
type test struct {
Id string `bson:"_id"` <---- how to define composite key that I want to use as key in new collection
X string `bson:x`
Y string `bson:y`
}
I hope my question is clear, I can add more information if required to answer this.
答案1
得分: 3
找到解决方法,如果有人遇到相同问题,我来回答一下。
你可以为复合键创建另一个结构体。
type key struct {
a string
b string
c int
}
type test struct {
Id key `bson:"_id"` // 在新集合中定义要用作键的复合键的方法
X string `bson:"x"`
Y string `bson:"y"`
}
希望对你有帮助!
英文:
Figured it out, answering to help if someone runs into the same.
You can created another struct for composite key.
type key struct {
a string
b string
c int
}
type test struct {
Id key `bson:"_id"` <---- how to define composite key that I want to use as key in new collection
X string `bson:x`
Y string `bson:y`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论