Reputation: 13
The following example performs an unordered insert of three documents. With unordered inserts, if an error occurs during an insert of one of the documents, MongoDB continues to insert the remaining documents in the array:
db.products.insert(
[
{ _id: 20, item: "lamp", qty: 50, type: "desk" },
{ _id: 21, item: "lamp", qty: 20, type: "floor" },
{ _id: 22, item: "bulk", qty: 100 }
],
{ ordered: false }
)
Is this possible with mongolite? I am using a dataframe to insert data into mongo.
Upvotes: 1
Views: 547
Reputation: 65323
The mongo
shell converts multiple insert statements into a bulk insert operation, which is where the ordered vs unordered behaviour applies. The Bulk API was introduced in MongoDB 2.6; older versions of MongoDB had a batch insert API which had an option to "continue on error" that defaulted to false
.
The mongolite
R package builds on the officially supported libmongoc
driver, but as at mongolite 1.2
does not properly expose an option to control the behaviour of bulk inserts. However, the underlying mongolite
C functions do have a stop_on_error
boolean (default: TRUE
) which maps to ordered vs unordered inserts.
I've submitted a pull request (mongolite #99) which will pass through the stop_on_error
parameter for bulk inserts.
This doesn't change the default mongolite
behaviour, which will be to stop at the first error encountered in a bulk insert. With stop_on_error
set to FALSE
, errors will be summarised for each batch of bulk inserts.
Sample usage (where data
could be any valid parameter for insert()
such as a data frame, named list, or character vector with JSON strings):
coll$insert(data, stop_on_error = FALSE)
It may make more sense to rename the parameter from stop_on_error
to ordered
for consistency with the bulk API, but I'll leave that to the discretion of the mongolite
maintainer.
Upvotes: 1