2
votes

I am having difficulty batch saving MongoDB documents using the C# driver. Here's sample code that inserts a Document with a GUID BsonID. Saving one at a time works. If I insert the documents into a list and use the save command it fails with an "Save can only be used with documents that have an Id." error. Any thoughts?

var autolookuplist = new List<BsonDocument>();
            Parallel.ForEach(docs, webdoc =>
                {
                    lock (autolookuplist)
                    {
                        autoID++;
                        var hold = new APAUtoIDGuidLookup() {AutoIncrementID = autoID, ID = webdoc.ID};
                      autolookuplist.Add(hold.ToBsonDocument());
                    }

                  //this works
                 //   idcollection.Save(new APAUtoIDGuidLookup() { AutoIncrementID = autoID, ID = webdoc.ID });
                });


          //this doesn't work
          idcollection.Save(autolookuplist);

here's the document class

public class  APAUtoIDGuidLookup
{
    [BsonId]
    public Guid ID { get; set; }
    public int AutoIncrementID { get; set; }
}

Update: It doesn't look like MongoDB supports batch updates.

1
An unrelated observation: you are using Parallel.ForEach and you are immediately synchronizing your access to the autolookuplist via the lock statement. This doesn't make much sense or am I missing something?tobsen

1 Answers

3
votes

You can't do a batch save, but you can do a batch insert.

idcollection.InsertBatch(autolookuplist);