mongodb - Unique array value in Mongo -


i'm having hard time find way make collection index work way need. collection has array contain 2 elements, , no other array can have these 2 elements (in order):

db.collection.insert(users : [1,2] // should valid db.collection.insert(users : [2,3] // should valid db.collection.insert(users : [1,3] // should valid db.collection.insert(users : [3,2] // should invalid, since there's array same value. 

but, if use db.collection.createindex({users:1}, {unique: true}), won't allow me have 2 arrays common element:

db.collection.insert(users : [1,2] // valid db.collection.insert(users : [2,3] // invalid, since 2 on document 

one of solutions tried make array 1 level deeper. creating same index, adding documents little different make way need, still allow 2 arrays have same value in reverse orders:

db.chat.insert({ users : { people :  [1,2] }}) // valid db.chat.insert({ users : { people :  [2,3] }}) // valid db.chat.insert({ users : { people :  [2,1] }}) // valid, should invalid, since there's document [1,2] array value. db.chat.insert({ users : { people :  [1,2] }}) // invalid 

is there way achieve on index level?

the mongodb doesn't create indexes on entire array. but...

we want 1 atomic operation insert or update, , guarantee uniqueness of array's content? then, need calculate one feature same for all permutations of array's items, , create unique index it.

one way sort array items (solves permutation problem) , concatenate them (creates 1 feature). example, in javascript:

function index(arr) {   return arr.sort().join(); }  users1 = [1, 2], usersindex1 = index(users1); // "1,2" users2 = [2, 1], usersindex2 = index(users2); // "1,2"  // create index db.collection.ensureindex({usersindex: 1}, {unique: true}); //  db.collection.insert({users: users1, usersindex: usersindex1}); // ok db.collection.insert({users: users2, usersindex: usersindex2}); // error 

if arrays long, can apply hash function on strings, minimizing size of collection. though, comes price of possible collisions.


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -