iCode
iCode

Reputation: 4338

Adding Batch Upsert to MongoDB.

It looks like MonogoDB does not support batch upsert. Is this Correct?

If not, how would you go about adding batch upsert with the existing API which is the most efficient? Does batch upsert even make sense for mongo db?

Upvotes: 13

Views: 7567

Answers (3)

rnofenko
rnofenko

Reputation: 9533

For C# MongoDB.Driver I use next:

        var writeModels = new List<WriteModel<T>>();
        foreach (var entity in list)
        {
            var id = entity.Id;
            if (id == null)
            {
                writeModels.Add(new InsertOneModel<T>(entity));
            }
            else
            {
                var filter = new ExpressionFilterDefinition<T>(x => x.Id == id);
                var replaceModel = new ReplaceOneModel<T>(filter, entity);
                writeModels.Add(replaceModel);
            }
        }
        await getCollection().BulkWriteAsync(writeModels);

Upvotes: 1

Vlad Mihalcea
Vlad Mihalcea

Reputation: 153810

If you upgrade to MongoDB 2.6 you can take advantage of the new Bulk operations:

Bulk.find(<query>).upsert().update(<update>);
Bulk.find(<query>).upsert().updateOne(<update>);
Bulk.find(<query>).upsert().replaceOne(<replacement>);    

Upvotes: 2

JB.
JB.

Reputation: 861

There is a utility called mongoimport that has an upsert flag. Something like

mongoimport -c myitems -d mydb --upsert items.json

Could this possibly achieve what you are looking for?

The default is to upsert based upon _id but you can change that using the --upsertFields flag documented here

http://docs.mongodb.org/manual/reference/mongoimport/#cmdoption-mongoimport--upsertFields

Upvotes: 1

Related Questions