Clear Filters
Clear Filters

Switching the mongodb database in an existing connection using the MongoDB C++ interface

4 views (last 30 days)
I use Matlab together with MongoDB to store computation results.
The MongoDB server contains multiple databases, but authentication is always handled by the admin database.
Using the mongo function to create a connection, it is possible to switch the database of an existing connection:
conn = mongo('localhost',27017,'admin','UserName',user,'Password',password)
conn.Database = 'evaluation'
conn.ConnectionNames % this lists the collections of the 'evaluation' database
conn.insert('item', ...) % insert some documents
I am now trying to switch to the new MongoDB C++ interface by using the mongoc function to create the database connection.
The documentation states that the database can be switched after the connection is made in the same way as before.
However, running this code does not seem to work:
conn = mongoc('localhost',27017,'admin','UserName',user,'Password',password)
conn.Database = 'evaluation'
conn.ConnectionNames % this lists the collections of the 'admin' database
conn.insert('item', ...) % insert some documents
This throws the following error:
Error using database.mongo.connection/find (line 118)
Unable to find collection: item.
Is there some other way to switch the database of a connection made using the new C++ interface?

Answers (1)

Dinesh
Dinesh on 26 Dec 2023
Hi Elias,
If you are still facing this issue, please review the following to troubleshoot the issue:
  1. Please make sure that the appropriate 'mongoc' driver is downloaded and added to MATLAB path. Then after the line 'conn = mongoc(...', check if the connection is open successfully using 'isopen(conn)'.
  2. The error message mentioned that it is unable to find the collection "item", so the line where you change the database might not even be the cause for this error. You can refer to the documentation to see if the usage of "insert" is correct for "mongoc": https://www.mathworks.com/help/database/ug/mongoc.html
  3. In your code, the 3rd argument 'admin' is supposed to be the name of the database. If 'admin' is the database, then why are you changing the database in the very next line by specifying 'conn.Database' to be equal to 'evaluation'? Is it just a test code to see if changing the database works? If you are certain that changing the database is the cause for the error, then please let me know in case you are still facing the issue.

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!