mongolite icon indicating copy to clipboard operation
mongolite copied to clipboard

How do I create a unique index?

Open bidwbb opened this issue 7 years ago • 9 comments
trafficstars

How do I create a unique index? Is it possible with mongolite?

bidwbb avatar Apr 19 '18 17:04 bidwbb

related another Question to @mongolite Team how do we specify our own Unique key value

psramkumar avatar May 01 '18 16:05 psramkumar

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.

gladkia avatar Dec 07 '18 16:12 gladkia

Is it available yet? how can we create an unique index?

popiula avatar Mar 02 '19 09:03 popiula

  1. @Popiula, the PR has not been merged so far. I am still waiting for the response from @jeroen.

  2. Please have a look into the R tests for examples how to create a unique index.

gladkia avatar Mar 18 '19 09:03 gladkia

Will there be progress in the future concerning unique indices?

martinschmelzer avatar Apr 16 '19 13:04 martinschmelzer

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

seventm avatar Nov 12 '19 14:11 seventm

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!

odeda avatar May 02 '20 17:05 odeda

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]}')

seventm avatar May 02 '20 20:05 seventm

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

odeda avatar May 03 '20 12:05 odeda