2

我需要使用比较运算符构建查询,相当于db.inventory.find( { qty: { $gt: 20 }使用官方驱动程序。知道怎么做吗?

4

1 回答 1

0

连接到服务器类似于:

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) }

然后获得inventory mongo.Collection类似:

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().

于 2018-07-12T22:54:36.310 回答