node.js - MongoDb:使用唯一索引插入或更新多个文档

标签 node.js mongodb mongojs

我有一个带有唯一索引的 MongoDB 集合。 我正在尝试将文档数组插入或更新到该集合中。

如果集合中没有与文档的唯一索引匹配的现有文档,则应将该新文档插入到集合中。

但是,如果集合中已经存在具有该唯一索引的文档,则应使用新文档的字段对其进行更新。新文档中不存在的任何字段都应保持不变。

这是我目前所拥有的,用于插入(但不适用于更新)。

const mongojs = require('mongojs');
const db = mongojs('mongodb://username:password@address.mlab.com:37230/database');

             // items is an array of documents
db.items.insert(items, (err, task) => {
    if (err) {
      console.log(err);
    }
  })

我知道这是错误的,它目前给出了这个错误:

E11000 duplicate key error index: database.items.$upc_1 dup key:

正确的查询是什么?

最佳答案

您可以尝试使用 mongodb bulkWrite api:

var ops = []

items.forEach(item => {
    ops.push(
        {
            updateOne: {
                filter: { _id: unique_id },
                update: {
                    $set: { fields_to_set_if_exists },
                    $setOnInsert: { fileds_to_insert_if_does_not_exist }
                },
                upsert: true
            }
        }
    )
})

db.collections('collection_name').bulkWrite(ops, { ordered: false });

关于node.js - MongoDb:使用唯一索引插入或更新多个文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42990475/

相关文章:

node.js - 如何在 Linux 托管 NodeJS 上打开 .exe 文件

node.js - 有没有人有一个很好的解决方案来将模块包装器与父项目分离?

mongodb - 处理请求时发生Grails-MongoDB-IndexOutOfBoundsException

MongoDb 从文档中删除子文档

node.js - mongoose 和 mongoJS 有什么区别?我应该使用哪个?

node.js - MS Cognitive Services 的面部 api 的 personGroup 保存在哪里?

node.js - Socket.io如何检查客户端的cookie数据?

mongodb - 如何在kubernetes中包含带有mongo图像的数据

node.js - Mongodb查找然后更新

Node.js + mongoDB,mongojs $in 运算符出错