mongodb 在重复项上插入多个文档是否使用新文档更新现有文档?

ev7lccsx  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(151)

在重复的唯一索引上插入多个文档(例如在一个命令中插入5,000个文档),在所有字段上用新文档更新现有文档的正确方法是什么?
例如,在5,000个文档中,1,792个文档是新的,没有唯一索引的重复项,因此它们被插入,而3,208个文档在集合中具有唯一索引的重复项,这些重复项应该被替换为所有值的现有文档。
我尝试了insertMany()与无序选项,但它似乎跳过重复的文档。
那么updateMany()upsert:true不是用于插入多个文档,而是仅用于更新集合中的某些字段吗?
这可能吗?
=========示例======
对于具有字段“name”的唯一索引的业务集合:

{"name":"Google", "address":"...", "employees":38571, "phone":12345}
{"name":"Microsoft", "address":"...", "employees":73859, "phone":54321}
{"name":"Apple", "address":"...", "employees":55177, "phone":88888}
{"name":"Meta", "address":"...", "employees":88901, "phone":77777}

现在,我们要使用以下4个文档更新集合:

{"name":"Apple", "address":"...", "employees":55177, "phone":22222}
{"name":"Dell", "address":"...", "employees":77889, "phone":11223}
{"name":"Google", "address":"...", "employees":33333, "phone":44444}
{"name":"IBM", "address":"...", "employees":77777, "phone":88888}

在MySQL中,我可以在一个查询中完成此操作:

INSERT INTO business (name, address, employees, phone)
    VALUES
    ('Apple', '...', 55177, 22222),
    ('Dell', '...', 77889, 11223),
    ('Google', '...', 33333, 44444),
    ('IBM', '...', 77777, 88888)
    AS new
ON DUPLICATE KEY UPDATE
    address = new.address
    employees = new.employees
    phone = new.phone

收款单据变为:

{"name":"Google", "address":"...", "employees":33333, "phone":44444} # updated
{"name":"Microsoft", "address":"...", "employees":73859, "phone":54321} # no change
{"name":"Apple", "address":"...", "employees":55177, "phone":22222} # updated
{"name":"Meta", "address":"...", "employees":88901, "phone":77777} # no change
{"name":"Dell", "address":"...", "employees":77889, "phone":11223} # inserted
{"name":"IBM", "address":"...", "employees":77777, "phone":88888} # inserted

如何在MongoDB中执行此操作?

ni65a41a

ni65a41a1#

您可能只需要$merge。将您需要浏览的文档放到另一个集合中(称为toBeInserted)。$merge toBeInserted到现有集合中。

db.toBeInserted.aggregate([
  {
    "$project": {
      // select the relevant fields
      _id: 0,
      name: 1,
      address: 1,
      employees: 1,
      phone: 1
    }
  },
  {
    "$merge": {
      "into": "companies",
      "on": "name",
      "whenMatched": "merge",
      "whenNotMatched": "insert"
    }
  }
])

Mongo Playground

相关问题