DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Join us tomorrow at 1 PM EST: "3-Step Approach to Comprehensive Runtime Application Security"
Save your seat
  1. DZone
  2. Data Engineering
  3. Databases
  4. Bulk Insert in MongoDB With a C# Driver [Code Snippet]

Bulk Insert in MongoDB With a C# Driver [Code Snippet]

In this post we take a look at how to efficiently save a large collection of documents in Mongo. Read on for details.

Ricci Gian Maria user avatar by
Ricci Gian Maria
·
Nov. 05, 16 · Code Snippet
Like (2)
Save
Tweet
Share
8.44K Views

Join the DZone community and get the full member experience.

Join For Free

There are situations where you need to save a lot of documents inside a collection in MongoDB. My scenario is a migration of documents from a collection to another database, with in-memory manipulation of the documents.

The most common error in these situations is to read the documents from the original collection, then execute a function that modify the document in-memory, and finally issuing an insert in destination collection. This is wrong because you have a roundtrip against MongoDB for each document you are saving.

Whenever you are calling Insert or Save function, you are paying the penality of a call to MongoDb process, network latency, etc, whenever possible you should reduce the number of calls to database engine.

In such a scenario, the MongoDB driver has a function called InsertBatch that allows you to insert documents in batches — and the fun part is that it simply accepts an IEnumerable. As an example, I have a function that manipulates a BsonDocument stored in a variable called Action. I have source and test database where I need to copy documents with manipulation and this is the code that does everything.

var sourceQueue = source.GetCollection(queue);
var destQueue = dest.GetCollection(queue);

if (sourceQueue.Count() == 0) return;

//migrate counterCollection
Console.WriteLine("Migrating Queue " + queue);
var allElement = sourceQueue
.FindAll()
.AsEnumerable()
.Select(document => {
    Action(document);
    return document;
});
destQueue.InsertBatch(allElement);

The name of the collection is contained in queue variable (actually I’m transforming a software that manages jobs), and as you can verify I can simply enumerate all source documents with FindAll (this code uses the old 1.10 driver), for each object I’m calling the Action function that manipulates the document, and finally I can simply use the InsertBatch to insert documents in batches.

This function runs faster than saving each document with a separate call, even if the MongoDB instance runs on the very same machine, so you do not pay the network latency.

If you use the latest version of the drivers, you have the InsertMany method that offers even more options and basically does the very same operation as InsertBatch.

MongoDB Driver (software) Document Snippet (programming)

Published at DZone with permission of Ricci Gian Maria, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top Five Tools for AI-based Test Automation
  • Visual Network Mapping Your K8s Clusters To Assess Performance
  • Why Does DevOps Recommend Shift-Left Testing Principles?
  • Core Machine Learning Metrics

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: