By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,952 Members | 1,616 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,952 IT Pros & Developers. It's quick & easy.

MongoDB Upsert

P: 8
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

Expand|Select|Wrap|Line Numbers
  1. /* 0 */
  2. {
  3.   "_id" : ObjectId("5205344a405a280bf8f3b1c5"),
  4.   "mykey" : 1000,
  5.   "data" : [
  6.     {
  7.       "d" : 20130807
  8.       ...
  9.     }, 
  10.     {
  11.       "d" : 20130806
  12.       ...
  13.     }]
  14. }
  15.  

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

Expand|Select|Wrap|Line Numbers
  1. Dim query = New QueryDocument()
  2. query.Add(New BsonElement("mykey" mykeyid))
  3.  
  4. Dim count As Integer = mongo_collection.Count(query)
  5.  
  6. If count > 0 Then
  7.  
  8.     Dim query2 = New QueryDocument()
  9.     query2.Add(New BsonElement("mykey", mykeyid))
  10.     query2.Add(New BsonElement("data.d", [date]))
  11.  
  12.     count = mongo_collection.Count(query2)
  13.  
  14.     If count > 0 Then
  15.         mongo_collection.Update(query2, Update.Set("data.$", bson("data")(0)))
  16.     Else
  17.         mongo_collection.Update(query, Update.Push("data", bson("data")(0)))
  18.     End If
  19.  
  20.  
  21. Else
  22.   mongo_collection.Insert(bson)
  23. End If
  24.  
  25.  
Aug 9 '13 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.