使用golang和mongodb进行顺序查询

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

Sequential queries with golang & mongodb

问题

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

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

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

  1. 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 :

  1. result *bson.M
  2. ids:=["543d171c5b2c12420dd016","543d171c5b2dd016"]
  3. oids := make([]bson.ObjectId, len(ids))
  4. for i := range ids {
  5. oids[i] = bson.ObjectIdHex(ids[i])
  6. }
  7. query := bson.M{"_id": bson.M{"$in": oids}}
  8. 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?

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

答案1

得分: 0

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

  1. var docs []bson.M
  2. if err := c.Find(query).All(&docs); err != nil {
  3. // 处理错误
  4. }
  5. docIDs := make([]interface{}, len(docs))
  6. for i := range docs {
  7. docIDs[i] = docs[i]["_id"]
  8. }
  9. 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.

  1. var docs []bson.M
  2. if err := c.Find(query).All(&docs); err != nil {
  3. // handle error
  4. }
  5. docIDs := make([]interface{}, len(docs))
  6. for i := range docs {
  7. docIds[i] = docs[i]["_id"]
  8. }
  9. 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:

确定