Use Rs mongolite to correctly (insert? update?) add data to existing collection Use Rs mongolite to correctly (insert? update?) add data to existing collection mongodb mongodb

Use Rs mongolite to correctly (insert? update?) add data to existing collection


When you attempt to insert documents into MongoDB that already exist in the database as per their primary key you will get the duplicate key exception. In order to work around that you can simply unset the _id column using something like this before the con$insert:

my.dataframes[i]$_id <- NULL

This way, the newly inserted document will automatically get a new _id assigned.


you can use upsert ( which matches document with the first condition if found it will update it, if not it will insert a new one, first you need to separate id from each doc

 _id= my.dataframes[i]$_id updateData = my.dataframes[i] updateData$_id <- NULL

then use upsert ( there might be some easier way to concatenate strings in R)

 con$update(paste('{"_id":"', _id, '"}' ,sep="" ) , paste('{"$set":', updateData,'}', sep=""), upsert = TRUE)