使用Rs mongolite正确(插入?更新?)将数据添加到现有集合中

Can*_*ice 5 r mongodb mongolite

我有以下用R编写的函数(我认为)在更新我的mongo数据库集合方面做得很差。

library(mongolite) 

con <- mongolite::mongo(collection = "mongo_collection_1", db = 'mydb', url = 'myurl')
myRdataframe1 <- con$find(query = '{}', fields = '{}')
rm(con)

con <- mongolite::mongo(collection = "mongo_collection_2", db = 'mydb', url = 'myurl')
myRdataframe2 <- con$find(query = '{}', fields = '{}')
rm(con)

... code to update my dataframes (rbind additional rows onto each of them) ...

# write dataframes to database
write.dfs.to.mongodb.collections <- function() {

  collections <- c("mongo_collection_1", "mongo_collection_2") 
  my.dataframes <- c("myRdataframe1", "myRdataframe2")

  # loop dataframes, write colllections
  for(i in 1:length(collections)) {

    # connect and add data to this table
    con <- mongo(collection = collections[i], db = 'mydb', url = 'myurl')
    con$remove('{}')
    con$insert(get(my.dataframes[i]))
    con$count()

    rm(con)
  }
}
write.dfs.to.mongodb.collections()
Run Code Online (Sandbox Code Playgroud)

我的数据框myRdataframe1myRdataframe2是非常大的数据框,目前有约10万行和约50列。每次我的脚本运行时,它:

  • 使用con $ find('{}')将mongodb集合拉入R,另存为数据框 myRdataframe1
  • 从数据提供程序中刮取新数据,该数据将作为新行附加到 myRdataframe1
  • 使用con $ remove()和con $ insert 完全删除 mongodb集合的数据,然后重新插入整个myRdataframe1

最后一点很不明确,因为我每天都在cronjob中运行此R脚本,而每次我完全擦除mongo db集合并将R数据帧重新插入到集合中时,我都不喜欢这样做。

如果删除con $ remove()行,则会收到一条错误消息,指出我有重复的_id键。看来我不能简单地使用con $ insert()追加。

任何想法对此表示赞赏!

dni*_*ess 2

当您尝试根据主键将数据库中已存在的文档插入 MongoDB 时,您将收到重复键异常。为了解决这个问题,您可以简单地_id在以下内容之前使用类似的内容取消设置列con$insert

my.dataframes[i]$_id <- NULL
Run Code Online (Sandbox Code Playgroud)

这样,新插入的文档将自动获得新的_id分配。