2

我在一个小项目中,Mongo 数据库有一些与其他集合有一对多关系的集合。

假设我有一个名为的集合Company,它与 1 对多的关系Employee。在 R 中,如果我刚刚创建了一个公司实例,并且我做了类似的事情returnValue <- companyCollection$insert(Company),我想获得一个返回值,该值指示objectId新插入的公司是什么。我想要这个,因为我计划创建Employee一个实例,该实例具有一个名为companyId该字段的字段,该字段将该公司的objectId 字段作为字段。objectId使用 mongolite 将 1 个条目插入集合时,有什么方法可以返回?

我知道如果直接使用 mongo,您可以使用它db.collection.insertOne()来获取对象 ID,但我看不到使用 R 的 mongolite 包装器的此类选项。

如果这对 mongolite 是不可能的,那么如何指定 '_id' 属性,以便在将条目插入集合时,mongo 将其视为类型“ObjectID”而不是“String”?目前,如果我提供自己的 _id,mongo 会将 _id 视为字符串而不是对象 ID。Mongo 指南针将我插入的文档 ID 显示为:

mongo 将提供的 _id 视为

而不是这个:

mongo生成的_id,其实是type

4

1 回答 1

3

在将文档插入集合时,我无法找到获取生成的对象 ID 的方法,但我最终只是使用了一种解决方法。解决方法是在您的文档中有一个具有 UUID 的临时字段,然后使用该 uuid 再次查找该对象。之后,您可以获取_idmongo 生成并删除创建的临时字段。这是一个执行此操作的函数。

# an example of a collection
myTableCollection<- mongo("myTable", url = "mongodb://localhost:27017/myDatabase")

# This is a function to insert a dataframe into mongo collection as a document, 
# and get back the ObjectID that was generated by mongo
storeIntoCollection <- function(document, collection){

    # so create a temporary ID to find the entry in the database again
    temp <- UUIDgenerate()
    document$creationID <- temp


    # insert the DB Object
    returnValue = collection$insert(document)

    # query string to look up object using temp id
    id_string <- paste('{"creationID" : "' , temp , '"}', sep="")

    # Get mongo DB object just inserted
    insertedDocument = collection$find(id_string, field = '{}')

    # delete the temporary 'creationID' field
    update_string <-  paste('{ "$unset" : {"creationID": ""} }', sep="")
    collection$update(id_string, update_string)

    # turn '_id' to 'id'
    colnames(document)[colnames(document)=="_id"] <- "id"

    return(insertedDocument$id)
}
于 2019-03-05T18:53:05.123 回答