如果我有该文件:
{ accounts: [1, 2] }
我应该无法添加新文档
{ accounts: [2, 1] }
但我应该能够添加
{ accounts: [1, 3] }
有什么方法可以创建这样的唯一索引吗?我当前的解决方案是检查它的子集是否尚未定义。
最佳答案
您可以利用$all构建查询条件的运算符,
db.col.update({ accounts: { $not: { $all: [2, 1] } } }, { $push: { accounts: { $each: [ 2, 1 ] } } }) // will return no match
同时
db.col.update({ accounts: { $not: { $all: [1, 3] } } }, { $push: { accounts: { $each: [ 1, 3 ] } } })
将成功更新您的文档,因为 accounts
数组中并非存在所有元素
编辑:
为了防止插入文档,您需要一个带有 unique
参数的索引。默认情况下,MongoDB 为数组的每个元素创建单独的索引条目,这意味着您只能插入 1
一次。作为解决方法,您可以尝试使用数组索引创建复合索引:
db.col.createIndex( { "accounts.0": 1, "accounts.1": 1 }, { unique: true } )
这要求数字对是唯一的,但顺序很重要,因此您必须强制应用程序将帐户
作为有序数组插入。
关于javascript - mongodb基于数组的唯一索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53803368/