I want to use the MongoDB Rust Driver to bulk-insert documents into a collection. I have a bulk
vector that I fill and flush when reaching a given size.
My issue is that I must .clone()
the vector when giving it to driver's API bulk_write()
.
If I don't clone, I have a E0382: use after move error, and it seems that the API don't accept reference (E0308: expected struct std::vec::Vec
, found reference).
I'm new to Rust. Is there a way to do it without cloning this big structure? (structure is not big in my sample, but is in my actual code)
There's my code:
// Cargo.toml extract:
//
// [dependencies]
// bson = "0.10"
// mongodb = "0.3.7"
#[macro_use(bson, doc)] extern crate bson;
extern crate mongodb;
use mongodb::coll::options::WriteModel;
use mongodb::{Client, ThreadedClient};
use mongodb::db::ThreadedDatabase;
fn main() {
// Connect to MongoDB and select collection
let client = Client::connect("localhost", 27017).ok().expect("Failed to initialize client.");
let coll = client.db("test").collection("mycol");
// Make the bulk vector
let mut bulk = Vec::new();
for i in 0..1000 {
// Append a item to the bulk
bulk.push(WriteModel::UpdateOne { filter: doc!{"_id": i},
update: doc!{"$set" => {"hello" => "world"}},
upsert: Some(true) });
// Each 11 items, flush bulk
if bulk.len() > 10 {
println!("Upsert {} docs into collection...",bulk.len());
// `bulk` have to be cloned here
let result = coll.bulk_write(bulk.clone(), true); // Unoptimal: bulk cloned
//let result = coll.bulk_write(bulk, true); // E0382: use after move
//let result = coll.bulk_write(&bulk, true); // E0308: expected struct `std::vec::Vec`, found reference
// Check result
match result.bulk_write_exception {
Some(exception) => {
if exception.message.len()>0 {
println!("ERROR: {}",exception.message);
}
}
None => ()
}
bulk.clear();
}
}
// Final flush
if bulk.len() > 0 {
println!("Upsert {} docs into collection...",bulk.len());
let result = coll.bulk_write(bulk.clone(), true);
match result.bulk_write_exception {
Some(exception) => {
if exception.message.len()>0 {
println!("ERROR: {}",exception.message);
}
}
None => ()
}
}
}