確實是使用Collection.update: update(selector, document, options, callback)Updates documents. Name Type Degault Description selector object The selector for the update operation. document object The update document. options object null [optional] Optional settings. callback Collection~writeOpCallback [optional] The command result callback 在options中有一個upsert屬性(Type: boolean),用於確定這是否是一個 upsert 操作。即但不存在selectop匹配的文檔時,是否插入文檔。 name相同則更新,不同則插入: 代碼應該是這樣的: var urDocument = { // 你想插入的文檔 name: "joasn", other: "ohaedoaduantoduntaodutaod" }; var MongoClient = require('mongodb').MongoClient, MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var collection = db.collection('collocation'); collection.update({name: {$ne: urDocument.name}, {upsert: true}, urDocument); }); name相同則不作為,不同則插入: var UrDocument = { // 你想插入的文檔 name: "joasn", other: "ohaedoaduantoduntaodutaod" }; var MongoClient = require('mongodb').MongoClient, MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { var collection = db.collection('collocation'); collection.findOne({name: urDocument.name }) .then(doc => doc ?? collection.insertOne(urDocument)); });
確實是使用
Collection.update:在
options中有一個upsert屬性(Type: boolean),用於確定這是否是一個 upsert 操作。即但不存在selectop匹配的文檔時,是否插入文檔。name相同則更新,不同則插入:代碼應該是這樣的:
name相同則不作為,不同則插入: