2

Say if I have the document:

{ accounts: [1, 2] }

I should not be able to add a new document

{ accounts: [2, 1] }

but I should be able to add

{ accounts: [1, 3] }

is there some way to create a unique index like this? My current solution is to check that it's a subset is not already defined.

3 Answers 3

2

You can take advantage of $all operator building your query condition,

db.col.update({ accounts: { $not: { $all: [2, 1] } } }, { $push: { accounts: { $each: [ 2, 1 ] } } }) // will return no match

while

db.col.update({ accounts: { $not: { $all: [1, 3] } } }, { $push: { accounts: { $each: [ 1, 3 ] } } })

will succesfully update your document since not all elements are present in accounts array

EDIT: To prevent inserting the document you need an index with unique parameter. By default MongoDB creates separate index entries for every element of the array which means that you will be able to insert 1 only once. As a workaroung you can try to create compound index using array index:

db.col.createIndex( { "accounts.0": 1, "accounts.1": 1 }, { unique: true } )

This requires pairs of numbers to be unique but order matters here so you have to enforce your application to insert accounts as ordered array.

Sign up to request clarification or add additional context in comments.

3 Comments

Ah sorry i meant add it as a new document in a collection.
@A.Lau modified my answer, this is kind of workaround so I'm not sure if that helps in your case
unfortunately the order does matter, as I'm doing a kind of friends connection thing. So the first element is always the requester and the second element is the requestee. So if the status is "pending", then the second element should be the user who has the "accept" and "decline" option, while the first element would only get the "cancel" option.
0

You can try using $addToSet. It will ensure that the array contains all unique values.

https://docs.mongodb.com/manual/reference/operator/update/addToSet/

Is this what you want?

Comments

0

unique indexes (arrays included) are described pretty well in Mongo's docs here, did you read them?

BTW if you explain the problem, you would get better feedback.

I guess your solution could work if you don't need to have > 1 document with null key (consult the manual). Arrays are treated as sets, so if [1, 2] is present, [2, 1] will be rejected in the presence of unique index.

1 Comment

how about you read the most upvoted answer first before posting your own answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.