javascript - mongodb基于数组的唯一索引

标签 javascript mongodb

如果我有该文件:

{ 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/

相关文章:

javascript - Mongo forEach 函数只在第一行执行更新

ruby-on-rails - Heroku 的 Rails、Mongoid 和 Unicorn 配置

javascript - 当 multipule 运行时,将加载图标附加到 Table TD 以进行 ajax 调用会混淆

javascript - NodeJS 中的异步与同步

javascript - 将 Summernote 与 Meteor 结合使用(发现 Meteor)

Mongodb 将聚合组值作为键

javascript - 如何衡量用户的访问时间

javascript - 为映射的 true 或 false 值的集合返回 true/false

javascript - 在年份的下拉列表中获取当前年份

mysql - Grails 2.5.0 + mongo + hibernate