mongodb-erlang icon indicating copy to clipboard operation
mongodb-erlang copied to clipboard

How to get collection names in the database?

Open BlaCatRu opened this issue 7 years ago • 5 comments

Help pls

  • "mc_worker_api:command(Connection,{<<"listDatabases">>,1})" works fine and returns a basic info about all existing databases
  • but listCollections command has another output and returns the cursor and the first batch

How cat I get results similar to the db.getCollectionNames method?

BlaCatRu avatar Feb 02 '17 16:02 BlaCatRu

Hi, You can get all the results from cursor by calling mc_cursor:rest/1

comtihon avatar Feb 02 '17 18:02 comtihon

Hi, There is another kind of the cursor i think. And mc_cursor:rest/1 fails :-(

{ok,<0.120.0>}
2> {true, Res} = mc_worker_api:command(Connection,{<<"listCollections">>,1}).
{true,#{<<"cursor">> => #{<<"firstBatch">> => [#{<<"idIndex">> => #{<<"key">> => #{<<"_id">> => 1},
               <<"name">> => <<"_id_">>,
               <<"ns">> => <<"xxxdb.xxx.collection">>,
               <<"v">> => 1},
             <<"info">> => #{<<"readOnly">> => false},
             <<"name">> => <<"xxx.collection">>,
             <<"options">> => #{},
             <<"type">> => <<"collection">>},
           #{<<"idIndex">> => #{<<"key">> => #{<<"_id">> => 1},
               <<"name">> => <<"_id_">>,
               <<"ns">> => <<"xxxdb.xxx.collection">>,
               <<"v">> => 1},
             <<"info">> => #{<<"readOnly">> => false},
             <<"name">> => <<"xxx.collection">>,
             <<"options">> => #{},
             <<"type">> => <<"collection">>}],
          <<"id">> => 0,
          <<"ns">> => <<"xxxdb.$cmd.listCollections">>}}}
3> mc_cursor:rest(Res).
** exception exit: {{function_clause,[{gen,do_for_proc,
...```

Description of this cursor from docs:
**listCollections.cursor**
A document that contains information with which to create a cursor to documents that contain    collection names and options. The cursor information includes the cursor id, the full namespace for the command, as well as the first batch of results.

BlaCatRu avatar Feb 03 '17 10:02 BlaCatRu

Thanks, I'll check it.

comtihon avatar Feb 06 '17 09:02 comtihon

@BlaCatRu did you ever figure it out?

dmsnell avatar Nov 18 '20 22:11 dmsnell

From my own exploration I believe that the response is returning the full list of collections inside of the <<"firstBatch">> field. I tried this on a database with a few hundred collections and it never indicated that there were more batches. Also the cursor id returned from the query seems to be invalid. I believe this is a special case for the commands.

dmsnell avatar Dec 16 '20 23:12 dmsnell