mongolite
mongolite copied to clipboard
How do I create a unique index?
How do I create a unique index? Is it possible with mongolite?
related another Question to @mongolite Team how do we specify our own Unique key value
Hi @psramkumar,
I've added support for unique indices here. This feature should be available in mongolite itself pretty soon, when the PR (link) is approved and merged.
Is it available yet? how can we create an unique index?
-
@Popiula, the PR has not been merged so far. I am still waiting for the response from @jeroen.
-
Please have a look into the R tests for examples how to create a unique index.
Will there be progress in the future concerning unique indices?
There is a simple solution... use run command:
mongo_connection$run('{"createIndexes": "collection_name", "indexes":[{"key":{"field_name":1}, "name": "my_new_index", "unique": true]}')
https://docs.mongodb.com/manual/reference/command/createIndexes/#dbcmd.createIndexes
There is a simple solution... use run command:
mongo_connection$run('{"createIndexes": "collection_name", "indexes":[{"key":{"field_name":1}, "name": "my_new_index", "unique": true]}')https://docs.mongodb.com/manual/reference/command/createIndexes/#dbcmd.createIndexes
Pretty old, but nevertheless I'm getting an error with this approach and am facing the same issue of trying to create a unique compound index using mongolite. Following mongodb docs: https://docs.mongodb.com/manual/core/index-unique/
m <- mongolite::mongo(mongo_url, collection = 'col', db = 'test')
m$run('{"db.col.createIndex( { "field_A": 1, "field_B": 1 }, { unique: true } )": 1}')
Error: Invalid JSON object: {"db.col.createIndex( { "field_A": 1, "field_B": 1 }, { unique: true } )": 1}
BTW, if there's a simpler way to create unique indexes (compound or otherwise) would be happy to know Thanks!
m <- mongolite::mongo(mongo_url, collection = 'col', db = 'test') mongo_connection$run('{"createIndexes": "col", "indexes":[{"key":{"field_A":1, "field_B": 1}, "name": "field_A_B_index", "unique": true]}')
m <- mongolite::mongo(mongo_url, collection = 'col', db = 'test') mongo_connection$run('{"createIndexes": "col", "indexes":[{"key":{"field_A":1, "field_B": 1}, "name": "field_A_B_index", "unique": true]}')
Thank you, that did It