How to ensure unique item in an array based on specific fields - mongoDB?

前端 未结 1 1764
有刺的猬
有刺的猬 2020-12-03 07:35

In my scenerio, there are authors in a collection, each author has messages and each message of author can has events. Each actor allowed to perfor

相关标签:
1条回答
  • 2020-12-03 08:11

    Mustafa, unique constraints are not enforced within a single array, although they're enforced among documents in a collection. This is a known bug that won't be fixed for a while:

    https://jira.mongodb.org/browse/SERVER-1068

    There's a workaround, though. Keep your unique index in place, and:

    1) Ensure your application does not insert new documents with duplicate values in the array. You can check for uniqueness in your application code before inserting.

    2) When updating existing documents use $addToSet instead of $push.

    0 讨论(0)
提交回复
热议问题