如何在MongoDB中更有效地运行此查询?

时间:2015-01-06 19:14:16

标签: .net vb.net mongodb database

我基本上做的是计算一个网址被查看的次数,每当某个用户在频道ID上查看某种网址时,我首先选择与此网址匹配的文档和此频道ID,

  • 如果不存在,创建它并将其计数设置为1,创建一个日期以指定生成时间并将其TTL设置为86400(基本上这意味着该文档将在一天内删除)。
  • 如果存在,请递增其计数字段并保存。

现在我看到了一些性能问题,我听说MongoDB上的更新操作会对它产生很大的影响,我怎么能以这样的方式实现它呢?它不会在数据库上如此沉重?

这是我正在使用的代码:

  Dim client = New MongoClient(MongoHelper.mongoRedirectConnectionString) 
        Dim domain As String = MerDecisionTaker.FixAddress(url)
        mongo = client.GetServer()
        db = mongo.GetDatabase("urls_check")
        table = db.GetCollection("urls_check")
        searchQuery = Builders.Query.And(Builders.Query.EQ("url", url), Builders.Query.EQ("channel", channel))
        tableNew = db.GetCollection("ForbiddenURLS")
        Dim forbiddenDocumentRedirect = tableNew.FindOneAs(Of MongoLiveNotifiedDocumentClass)(searchQuery)
        If (forbiddenDocumentRedirect Is Nothing) Then
            relevantObj = table.FindOneAs(Of MongoLiveNotifiedDocumentClass)(searchQuery)
            If (relevantObj Is Nothing) Then

                Dim settingsTable As MongoCollection = db.GetCollection("urls_checkSettings")

                Dim channelSettings = settingsTable.FindOneAs(Of channelSettings)(Builders.Query.EQ("channel", channel))
                If channelSettings Is Nothing Then
                    channelSettings = settingsTable.FindOneAs(Of channelSettings)(Builders.Query.EQ("channel", "channel"))
                End If
                If channelSettings IsNot Nothing Then
                    Dim newDoc As MongoLiveNotifiedDocumentClass = New MongoLiveNotifiedDocumentClass()
                    newDoc.date_created = DateTime.Now
                    newDoc.channel = channel
                    newDoc.url = url
                    newDoc.maxCount = channelSettings.maxCount
                    newDoc.Count = 1

                    If (url IsNot Nothing) Then

                        table.Insert(Of MongoLiveNotifiedDocumentClass)(newDoc)
                    End If
                End If

            Else
                If relevantObj.Count >= relevantObj.maxCount Then
                    Dim newDoc As MongoForbiddenURLDocumentClass = New MongoForbiddenURLDocumentClass()
                    newDoc.url = url
                    newDoc.channel = channel
                    tableNew.Update(searchQuery, Builders.Update.Replace(newDoc), MongoDB.Driver.UpdateFlags.Upsert)
                Else
                    relevantObj.Count += 1
                    table.Save(relevantObj)
                End If

            End If

        End If

有什么建议吗?

非常感谢!

0 个答案:

没有答案