形成一个结构来读取具有复合键的BSON对象。

huangapple go评论64阅读模式
英文:

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.

	&quot;$group&quot;: bson.M{
		&quot;_id&quot;: bson.M{
			&quot;a&quot;: &quot;$a&quot;,
			&quot;b&quot;: &quot;$b&quot;,
			&quot;c&quot;: &quot;$c&quot;,
		},
     x: &quot;x&quot;,
     y: &quot;y&quot; ..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:&quot;_id&quot;` &lt;---- 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:&quot;_id&quot;` &lt;---- how to define composite key that I want to use as key in new collection
X string `bson:x`
Y string `bson:y`
}

huangapple
  • 本文由 发表于 2015年10月8日 01:26:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/32998684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定