I can insert data into mongodb hosted at mongolabs from R but the moment I try to set the _id field I get this error:
> data<-list("_id"="1fgthhy2334",text="abc",nums=c(1,2,3))
> db$insert(data)
Error: can't use an array for _id
data<-list("_id"=c("12334"),text="abc",nums=c(1,2,3))
> db$insert(data)
Error: can't use an array for _id
Any idea why it thinks I'm trying to set the id to an array? None of my variations seem to work.
How can I set a particular _id field to my selected (unique) identifier?
if you do
jsonlite::toJSON(data)
# {"_id":["1fgthhy2334"],"text":["abc"],"nums":[1,2,3]}
you'll see it's converted internally to an array (as mongolite uses jsonlite to do the conversion)
To insert it as an object itself, you need the input data as a data.frame, something like
data <- data.frame("_id" = "1fgthhy2334", text = "abc", nums = c(1,2,3))
data <- aggregate(nums ~ X_id + text, data, list)
names(data)[1] <- "_id"
Now it gets converted to an object
jsonlite::toJSON(data)
# [{"_id":"1fgthhy2334","text":"abc","nums":[1,2,3]}]
so the insert should work
m <- mongo(collection = "test", db = "test")
m$insert(data)
# Complete! Processed total of 1 rows.
# $nInserted
# [1] 1
#
# $nMatched
# [1] 0
#
# $nRemoved
# [1] 0
#
# $nUpserted
# [1] 0
#
# $writeErrors
# list()
And as a sanity check, try and insert it again and it will fail because that _id already exists
m$insert(data)
Error: insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.test_id.$_id_ dup key: { : "1fgthhy2334" }