英文:
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}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论