Realm Sync, primary keys and partitions

Hi there

I was under the impression that primary keys need only to be unique per realm, but with sync it seems that all primary keys need to be unique per atlas db. Can you let me know if that’s true or i’m doing something wrong?

we have some objects that are stored in a synced realm. These objects are partitioned per user id (as an owner kind of pattern) and have an _id that is a string, however not an UUID or alike. It’s a unique id that combines several things. They are definitely unique per realm however each user would be able to create same object for their partition and hence have the same _id as some other user’s objects.

We have some roundabout workarounds to make those _ids include the userid for global uniqueness but this adds some super weird code and prevents easy updates with realm.add(.., update: .modified)

So, is it true that objects in an Atlas collection that a realm maps to need unique primary keys for all objects regardless of their partition field?

for example:

class FollowedTag: Object {
   @Persisted(primaryKey: true) var _id: String
   @Persisted var _partition: String
}

User1: FollowedTag(_id: "tag_123", _partition: "user1ID")
User2: FollowedTag(_id: "tag_123", _partition: "user2ID")

should sync to a realm containing only first object for user 1 and only second object for user 2, however i can’t get this to work as both _id s are the same

Any solution?

Primary keys must be unique per collection per the MongoDB documentation.

Thanks Ian

Can you point me to that documentation? There might be some examples there on my use case

The only thing i can find is this:

Primary keys are subject to the following limitations:

* You can define only one primary key per object model.
* Primary key values must be unique across all instances of an object in a realm. Realm Database throws an error if you try to insert a duplicate primary key value.
* Primary key values are immutable. To change the primary key value of an object, you must delete the original object and insert a new object with a different primary key value.
* [Embedded objects](https://docs.mongodb.com/realm/sdk/swift/data-types/embedded-objects/#std-label-ios-embedded-objects) cannot define a primary key.

(from https://docs.mongodb.com/realm/sdk/swift/fundamentals/object-models-and-schemas/)

Sure its more in the MongoDB docs, you can also see here in this blog post -