Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
error while inserting data into mongodb via R if try to set _id

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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" }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!