mercredi 3 septembre 2014

Unique Index on Array in MongoDB


Vote count:

0




Say we have a collection of documents similar to this:



{
foo: "Bar",
foos: [1, 2, 3]
}


I would like to define a unique index such that no document identical to this one can be inserted into the database.



db.stuffs.ensureIndex({ foos: 1 }, { unique: true })


Seems to block any document containing a foos array with any intersection, eg. if the document above was already in the database, then



{
foo: "Bar",
foos: [ 1 ]
}


Would also be blocked.



> db.stuffs.ensureIndex({ foos: 1 }, { unique: true })
> db.stuffs.insert({ foo: "Bar", foos: [ 1, 2, 3 ]})
> db.stuffs.insert({ foo: "Bar", foos: [ 1 ]})
E11000 duplicate key error index: test.stuffs.$foos_1 dup key: { : 1.0 }


I would like to be able to make insertions of [ 1, 2 ], [ 2, 1 ], [ 1, 3 ], etc. but not two [ 1, 2 ]



asked 44 secs ago

dave

48






Unique Index on Array in MongoDB

Aucun commentaire:

Enregistrer un commentaire