MongoDB Upsert

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • cryan
    New Member
    • Jan 2008
    • 8

    MongoDB Upsert

    Hello,

    I have nested BSON documents inside an array in the document. I would like to be able to add/update items without having to do so many queries to check if it exists. Is there an easier/more efficient way to do it? This is going to be done a few million times every hour.

    Example structure

    Code:
    /* 0 */
    {
      "_id" : ObjectId("5205344a405a280bf8f3b1c5"),
      "mykey" : 1000,
      "data" : [
        {
          "d" : 20130807
          ...
        }, 
        {
          "d" : 20130806
          ...
        }]
    }

    Example ------------------------

    Code:
    Dim query = New QueryDocument()
    query.Add(New BsonElement("mykey" mykeyid))
    
    Dim count As Integer = mongo_collection.Count(query)
    
    If count > 0 Then
    
        Dim query2 = New QueryDocument()
        query2.Add(New BsonElement("mykey", mykeyid))
        query2.Add(New BsonElement("data.d", [date]))
    
        count = mongo_collection.Count(query2)
    
        If count > 0 Then
            mongo_collection.Update(query2, Update.Set("data.$", bson("data")(0)))
        Else
            mongo_collection.Update(query, Update.Push("data", bson("data")(0)))
        End If
    
    
    Else
      mongo_collection.Insert(bson)
    End If
Working...