-
Notifications
You must be signed in to change notification settings - Fork 65
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Trying to insert entry with additional ObjectId fails #237
Comments
@kevinAlbs is there a way to create such a query with mongo-c-driver? |
Not directly. The only way insert an autogenerated ObjectID other than the bson_t *to_insert = bson_new ();
bson_oid_t oid;
bson_oid_init (&oid, NULL /* context */);
bson_append_oid (to_insert, "second_id", -1, &oid);
if (!mongoc_collection_insert_one (coll, to_insert, NULL /* opts */, NULL /* reply */, &error)) {
MONGOC_ERROR ("error in mongoc_collection_insert_one: %s", error.message);
return EXIT_FAILURE;
}
MONGOC_DEBUG ("insert OK");
bson_destroy (to_insert); Here is a runnable example. |
@kamilsi it looks like this is difficult to do with the R bindings. You will have to manually set the col <- mongo()
col$drop()
col$insert(iris)
iter <- col$iterate(query = '{}', fields = '{"_id":1}')
while(length(rec <- iter$one())){
selector <- sprintf('{"_id":{"$oid":"%s"}}', rec[['_id']])
second <- sprintf('{"$set":{"second_id": {"$oid": "%s"}}}', rec[['_id']])
col$update(selector, update = second)
}
out <- col$find(fields = '{}')
View(out) |
Converting string _id's into ObjectId()'s in a dplyr data frame.
Inserting a dplyr table with mongolite$insert, I used the following code to finally got it working (took me months... but this works). tbl <- imported_excel_tbl %>%
mutate(
clientcontract_id = list(list("$oid" = clientcontract_id))
)
coll$insert(tbl, auto_unbox = TRUE) So key elements are using the double list like `list(list("$oid" = clientcontract_id))' and the auto_unbox = TRUE with the insert else it won't work... Hope this helps others as well to insert an ObjectId() with a dataframe or a dplyr frame :-) JWR |
@Wesseldr I tried your code, but it inserted the field as string for me If you want to create a new document in a collection that has a custom objectID field – you have to:
No news on that? ..at least it works, I guess! |
finding myself here again while searching for a way to generate object id, i came up with this function which works for me and successfully inserts objectid into the table:
|
In e.g. MongoDB Compass you can insert a document that contains additional ObjectId. For example this JSON:
Will be translated to a document with two ObjectIds generated on the DB side, e.g:
This is handy if you are updating a document and want to have a unique identifier that changes after the update.
Unfortunately, you cannot reproduce this with
mongolite
:The text was updated successfully, but these errors were encountered: