【问题标题】:Collection insert multiple - ensure uniqueness集合插入多个 - 确保唯一性
【发布时间】:2016-10-10 14:59:30
【问题描述】:

主要目标是:一次插入多个文档,但确保集合中只存储唯一的文档解释如下

我像这样一次将许多文档插入到一个 mongodb 集合中:

db.users.insert([{name: 'Joe'}{'name': 'Bob'}]);

插入插入的某些值可能是重复的,我希望 MongoDB 忽略这些。这是为了确保集合内的唯一性。

db.users.insert([{name: 'Joe'}{'name': 'Jack'}]);

使用索引,如果整个插入不是唯一的而不是仅忽略非唯一项,则整个 .insert() 操作将失败。

db.users.createIndex({ 'name': 1 }, { unique: true });

来自 mongoDB 的日志:

BulkWriteResult({
    "writeErrors" : [
        {
            "index" : 0,
            "code" : 11000,
            "errmsg" : "E11000 duplicate key error collection: test.users index: name_1 dup key: { : \"Joe\" }",
            "op" : {
                "_id" : ObjectId("57f924ee7d864acfefaca700"),
                "name" : "joe"
            }
        }
    ],
    "writeConcernErrors" : [ ],
    "nInserted" : 0,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

还有其他方法吗?

【问题讨论】:

  • 你真正想要什么?你能详细说明一下吗
  • @WasiqMuhammad 我认为这个问题很清楚......我想一次插入多个文档,但确保只有唯一的文档存储在集合中。将此添加到问题帖子中

标签: javascript node.js mongodb mongodb-query


【解决方案1】:

忘记评论。也许你正在寻找这样的东西。 UnorderedBulkOp

神奇之处在于无序批量操作并行发生。如果其中一个(或一些)失败,MongoDB 将继续其余部分并在最后喊出错误。

【讨论】:

  • 我拥有的特定集合是一个有上限的集合,因此实际上订购操作很重要:(查看文档虽然似乎我可以使用有序的批量操作来代替?
  • 实际上这行不通。我现在明白你为什么在这里推荐无序批量操作了......If an error occurs during the processing of one of the write operations, MongoDB will return without processing any remaining write operations in the list.也许唯一的方法就是一个一个插入
【解决方案2】:

对于寻找答案的人。我最终使用批量update.upsert() 操作。这意味着我可以保留我的上限收藏,确保它已订购,并且整个操作仍然是散装的。

这消除了对唯一索引的需求,因为upsert 总是更新/插入数据,确保我们没有重复。 查找操作应包含唯一键。

const bulk = db.collection.initializeOrderedBulkOp();
bulk.find({name: 'Joe'}).upsert().updateOne({name: 'Joe'});
bulk.find({name: 'Bob'}).upsert().updateOne({name: 'Bob'});
bulk.find({name: 'Jack'}).upsert().updateOne({name: 'Jack'});
bulk.execute();

【讨论】:

    【解决方案3】:

    为了插入多个具有唯一键的文档,您可以创建一个索引,您可以在其中声明该键是唯一的。 就像您的情况一样,您可以使用此命令创建索引,

    db.users.createIndex({"name":1},{unique:true})

    【讨论】:

    • 那行字面上是在帖子中......我已经这样做了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-08
    相关资源
    最近更新 更多