0

I have a database of documents like that:

{
    "_id" : "37686aeb8d65e77665af55e69801a62c",
    "ip"  : "192.168.1.1",
    "mac" : "01:23:45:67:89:ab"
}

And I have a design doc with update handler. How can I check if a new document have an unique mac address? Is it possible in CouchDB?

Anthony
  • 12,407
  • 12
  • 64
  • 88
  • 2
    No, the update handler will not be able to check the unique-ness of a field. However, although not always an option, you can use the `_id` field to enforce unique-ness on a single field. – Dominic Barnes Jan 28 '13 at 22:52

1 Answers1

1

The only guaranteed unique value across database is the _id, so you have to set it as mac address if you'd like to delegate this control to CouchDB.

Otherwise, you have to handle it by your own through view function with map and reduce: map function emits mac address, reduce one groups them and counts. But the cost of this is additional view lookup before data adding and some logic for duplicates cleanup from your side, but you'll always have situations when duplicated values will be in database at the same time.

Kxepal
  • 4,659
  • 1
  • 19
  • 16
  • What he said. Except you could do it with just a view as well. Use the map function to give you documents by mac address. `emit(doc.mac, null);` and then hit that view with `?key="your_mac_address"` before you try to save anything. – fet Jan 29 '13 at 16:17
  • Yeah. Forgot to mention that this way also leads you to lose a lot of CouchDB features like replications, bulk updates, concurrent writes etc. You need to think twice if you really need this workaround. – Kxepal Jan 29 '13 at 22:46