使用golang和mongodb进行顺序查询

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

Sequential queries with golang & mongodb

问题

想知道在Golang中从MongoDB进行连续查询的最佳方法。
例如,假设你有以下代码:

result *bson.M
ids := ["543d171c5b2c12420dd016", "543d171c5b2dd016"]
oids := make([]bson.ObjectId, len(ids))
for i := range ids {
  oids[i] = bson.ObjectIdHex(ids[i])
}
query := bson.M{"_id": bson.M{"$in": oids}}
error := c.Find(query).All(&result)

你想要使用_ids的输出作为另一个表的查询条件。所以,以下代码是否正确?

query = bson.M{"_id": bson.M{"$in": result}}
英文:

Wondering what is best way to make sequential queries from Golang for a mongodb.
Example lets say you have :

result *bson.M
ids:=["543d171c5b2c12420dd016","543d171c5b2dd016"]
oids := make([]bson.ObjectId, len(ids))
for i := range ids {
  oids[i] = bson.ObjectIdHex(ids[i])
}
query := bson.M{"_id": bson.M{"$in": oids}}
error:= c.Find(query).All(&result)

And you want to take the output of the _ids and use it as a query for another table.
So is this correct?

query = bson.M{"_id": bson.M{"$in": result}}

答案1

得分: 0

以下是使用从其他查询返回的文档ID构建查询的方法:

var docs []bson.M
if err := c.Find(query).All(&docs); err != nil {
    // 处理错误
}
docIDs := make([]interface{}, len(docs))
for i := range docs {
    docIDs[i] = docs[i]["_id"]
}
query = bson.M{"_id": bson.M{"$in": docIDs}}

希望对你有帮助!

英文:

Here's how to construct a query using the ids of documents returned from some other query.

 var docs []bson.M
 if err := c.Find(query).All(&docs); err != nil {
    // handle error
 }
 docIDs := make([]interface{}, len(docs))
 for i := range docs {
    docIds[i] = docs[i]["_id"]
}
query = bson.M{"_id": bson.M{"$in": docIDs}}

huangapple
  • 本文由 发表于 2014年10月19日 15:55:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/26448537.html
匿名

发表评论

匿名网友

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

确定