Get ObjectID in mongolite R library
Asked Answered
H

3

6

I can successfully retrieve data from my mongoDB instance but need to re-use the objectID for a depending query.

The following code seems to get my entire object but NOT the id. What am I missing?

# Perform a query and retrieve data
mongoOBj <- m$find('{"em": "[email protected]"}')
Henrietta answered 18/12, 2015 at 16:59 Comment(0)
A
6

If you look at the documentation you see that the find method takes a field argument, where you specify the fields you want:

find(query = ’{}’, fields = ’{"_id" : 0}’, sort = ’{}’, skip = 0, limit = 0, handler = NULL, pagesize = NULL)

So in your case it will be something like

mongoOBj <- m$find(query = '{"em": "[email protected]"}', field = '{"_id": 1}')
Autolithography answered 20/12, 2015 at 17:18 Comment(0)
S
11

I realise this is an old question and OP has probably figured it out by now, but I think the answer should be

mongoOBj <- m$find(query = '{"em": "[email protected]"}', field = '{}') 

instead of

mongoOBj <- m$find(query = '{"em": "[email protected]"}', field = '{"_id": 1}')

In the second case, the result will be a data frame containing ONLY the IDs. The first line will result in a data frame containing the queried data, including the IDs.

By default, field = '{"_id": 0}', meaning _id is not part of the output.

Sateia answered 9/1, 2018 at 14:19 Comment(0)
A
6

If you look at the documentation you see that the find method takes a field argument, where you specify the fields you want:

find(query = ’{}’, fields = ’{"_id" : 0}’, sort = ’{}’, skip = 0, limit = 0, handler = NULL, pagesize = NULL)

So in your case it will be something like

mongoOBj <- m$find(query = '{"em": "[email protected]"}', field = '{"_id": 1}')
Autolithography answered 20/12, 2015 at 17:18 Comment(0)
H
1

FYI So the easiest way to get all fields is to do the query with field="{}". That will overwrite the default in the mongolite:: package find() arguments list.

It was driving me nuts for a little while too.

Hellebore answered 4/3, 2019 at 22:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.