在VB.net中Mongodb Driver 2.0 find()无效

时间:2015-04-23 17:55:42

标签: vb.net mongodb

我正在尝试使用C#Driver 2.0 for MongoDB。我不知道C#所以我在Visual Basic中编写代码。

当我尝试打印出列表代码时,将无法编译。我知道我已经注释了For Each内容,但这不是问题。我想查询数据库中的所有文档,并将它们打印到文本框中。

以下是无效的代码。最后一部分是给我带来麻烦。

Private Sub btnListUsers_Click(sender As Object, e As EventArgs) Handles btnListUsers.Click

    Dim ConnString As String
    ConnString = txtConnStr.Text

    Dim vDbName As String
    vDbName = txtDb.Text

    Dim vColName As String
    vColName = txtColl.Text

    Dim vClient As MongoClient

    vClient = DbConnection(ConnString, vDbName, vColName)

    Dim vDb As MongoDatabaseBase
    vDb = vClient.GetDatabase(vDbName)

    Dim vCol As IMongoCollection(Of BsonDocument)
    vCol = vDb.GetCollection(Of BsonDocument)(vColName)

    Dim query As BsonDocument
    query = New BsonDocument("Names", txtListUsers.Text)

    For Each item As BsonDocument In vCol.Find(query).ToListAsync()
        'print a count
        'print bson document

    Next

End Sub

感谢任何帮助。几个小时以来,我一直在敲击键盘。

以下是ALEX给我答复之后为我工作的代码:

Private Async Sub btnListUsers_Click(sender As Object, e As EventArgs) Handles btnListUsers.Click

        Dim ConnString As String
        ConnString = txtConnStr.Text

        Dim vDbName As String
        vDbName = txtDb.Text

        Dim vColName As String
        vColName = txtColl.Text

        Dim vClient As MongoClient

        vClient = DbConnection(ConnString, vDbName, vColName)

        Dim vDb As MongoDatabaseBase
        vDb = vClient.GetDatabase(vDbName)

        Dim vCol As IMongoCollection(Of BsonDocument)
        vCol = vDb.GetCollection(Of BsonDocument)(vColName)

        Dim query As BsonDocument
        query = New BsonDocument("Name", txtListUsers.Text)

        Dim myList As List(Of BsonDocument) = Await vCol.Find(query).ToListAsync()

        Dim i As Integer = 0

        For Each vItem As BsonDocument In myList

            'count
            i += 1

            'print bson document
            rtfDataDisplay.Text = rtfDataDisplay.Text & vbCrLf & "#" & i.ToString & " - " & vItem.ToString & vbCrLf

        Next

    End Sub

我必须将Async添加到sub。我的密钥“名称”也不正确。事情进展顺利。呜呜!

1 个答案:

答案 0 :(得分:0)

你的问题在这一行:

For Each item As BsonDocument In vCol.Find(query).ToListAsync()

ToListAsync()方法的调用返回一个等待的Task(Of List(Of BsonDocument)),即承诺它将返回一个列表,您可以在完成提取后枚举该列表。您需要Await才能进入列表。如:

Dim myList As List(Of BsonDocument) = Await vCol.Find(query).ToListAsync()
For Each item As BsonDocument in myList
    'print a count
    'print bson document
Next    

MongoDB驱动程序提供的替代构造是使用其ForEachAsync方法,并为其提供lambda委托参数。