将mongodb _id返回到data.frame

时间:2016-05-11 05:38:27

标签: r mongodb

school_id    <- mongo.distinct(mongo,dbns,"_id") ;
school_table <- data.frame(key=c(1:length(school_id)),ID=c(school_id))

第一个查询给我结果,即集合中存在的所有id的列表。 但是在尝试将此结果添加到数据框时。我收到了以下错误。

# Error in as.data.frame.default(x[[i]], optional = TRUE) :    cannot
# coerce class ""mongo.oid"" to a data.frame

请建议如何获取数据框中的ID列表。 提前致谢

1 个答案:

答案 0 :(得分:0)

您可以将ID转换为字符,然后放入data.frame

data.frame(key=c(1:length(school_id)),ID=do.call(rbind, lapply(school_id, as.character)))

考虑这个工作示例

## create dummy data and insert into database
library(rmongodb)
df <- data.frame(id = 1:10,
                 val =letters[1:10])


mongo <- mongo.create(db = "test")
coll <- "test.fetching_id"

## insert it a few times to gernate documents
for(i in 1:10){
    mongo.insert(mongo = mongo,
                ns = coll, 
                b = mongo.bson.from.df(df))
}


## find the data
raw_ids <- mongo.distinct(mongo = mongo,
                          ns = coll,
                          "_id")

mongo.destroy(mongo)

data.frame(key = c(1:length(raw_ids)), 
           ID = do.call(rbind, lapply(raw_ids, as.character)))

#   key                       ID
# 0   1 57562e6fceeb7846c87afd96
# 1   2 57562e6fceeb7846c87afd97
# 2   3 57562e6fceeb7846c87afd98
# 3   4 57562e6fceeb7846c87afd99
# 4   5 57562e6fceeb7846c87afd9a
# 5   6 57562e6fceeb7846c87afd9b
# 6   7 57562e6fceeb7846c87afd9c
# 7   8 57562e6fceeb7846c87afd9d
# 8   9 57562e6fceeb7846c87afd9e
# 9  10 57562e6fceeb7846c87afd9f