Unique Array in MongoDB Document

[{
"_id": 1,
"name": "group1",
"members": ["A", "B"]
}, {
"_id": 2,
"name": "group2",
"members": ["A", "C"]
}]
  • Can we add an unique index on members?
  • If the index type is regular, the answer is no.
  • Can db.group.find({members: ["B", "A"]}) find anything?
  • No, the array should be exactly matched.
  1. To find the content, we must know the order of members; otherwise, data cannot be retrieved.
  2. Similar to the problem one, even though this approach can make sure ["A", "B"] will not be duplicated, it cannot reject the insertion with ["B", "A"].
  3. The search pattern, regarding whether a single target exists in members, is inefficient. We have to use $in without the bound from an index to reduce the search scope.

Solution

[{
"_id": 1,
"name": "group1",
"members": [{"name": "A"}, {"name": "B"}]
}, {
"_id": 2,
"name": "group2",
"members": [{"name": "A"}, {"name": "C"}]
}]
  1. We don’t care the order of members when searching a group. We can just use db.group.find({$and: [{"members.name": "A"}, {"members.name": "B"}]}).
  2. We don’t care whether "A" is the former or the letter, it can be rejected correctly if there is indeed a group with "A" and "B".
  3. To find a group belongs to a specific member, we can use db.group.find({"members.name": "A"}). This can find out all groups "A" belongs.

Updated

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Chunting Wu

Chunting Wu

Architect at SHOPLINE. Experienced in system design, backend development, and embedded systems. Sponsor me if you like: https://www.buymeacoffee.com/MfGjSk6