【发布时间】:2018-07-12 21:08:57
【问题描述】:
我需要使用比较运算符构建查询,相当于使用official driver 的db.inventory.find( { qty: { $gt: 20 }。知道该怎么做吗?
【问题讨论】:
标签: mongodb go mongodb-query mongo-go
我需要使用比较运算符构建查询,相当于使用official driver 的db.inventory.find( { qty: { $gt: 20 }。知道该怎么做吗?
【问题讨论】:
标签: mongodb go mongodb-query mongo-go
连接到服务器类似于:
client, err := mongo.NewClient("mongodb://foo:bar@localhost:27017")
if err != nil { log.Fatal(err) }
err = client.Connect(context.TODO())
if err != nil { log.Fatal(err) }
然后获取inventorymongo.Collectionlike:
coll := client.Database("baz").Collection("inventory")
然后您可以使用Collection.Find() 执行查询,例如:
ctx := context.Background()
cursor, err := coll.Find(ctx,
bson.NewDocument(
bson.EC.SubDocumentFromElements("qty",
bson.EC.Int32("$gt", 20),
),
),
)
defer cursor.Close(ctx) // Make sure you close the cursor!
使用mongo.Cursor读取结果:
doc := bson.NewDocument()
for cursor.Next(ctx) {
doc.Reset()
if err := cursor.Decode(doc); err != nil {
// Handle error
log.Printf("cursor.Decode failed: %v", err)
return
}
// Do something with doc:
log.Printf("Result: %v", doc)
}
if err := cursor.Err(); err != nil {
log.Printf("cursor.Err: %v", err)
}
注意:我使用单个bson.Document 值来读取所有文档,并在每次迭代开始时使用其Document.Reset() 来清除它并“准备”它以将新文档读入其中。如果您想存储文档(例如,在切片中),那么您显然不能这样做。在这种情况下,只需在每次迭代中创建一个新文档,例如 doc := bson.NewDocument()。
【讨论】: