Reputation: 3272
I'd like to have a collection (test) to contain only one element. Therefore I have a update-query set to an empty object:
db.test.find() -> empty
var mongoData = {"name": "Biff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> {"name": "Biff", "_id":"1"}
var mongoData = {"name": "Buff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> {"name": "Buff", "_id":"1"}
Why isn't it this:
db.test.find() -> empty
var mongoData = {"name": "Biff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> {"name": "Biff", "_id":"1"}
var mongoData = {"name": "Buff"};
db.test.update({}, mongoData, {upsert:true}, cb);
db.test.find() -> [{"name": "Biff", "_id":"1"}, {"name": "Buff", "_id":"2"}]
Updating an empty object '{}' seems to ensure that there isn't created another element in this collection. I thought, that {} couldn't be found, so {"name":"Biff"} gets created and a _id is set to it. If I try to update {} another time, it is not creating {"name":"Biff"} again with a different _id. It is overwriting the only element in the collection. Why is this so?
Upvotes: 1
Views: 1334
Reputation: 7428
There is no problem here as MongoDB works like that. The insert
part of upsert
occurs only in case if the match criteria does not hit any document:
upsert: If set to true, creates a new document when no document matches the query criteria
So in your case, the find criteria (empty document {}
) matches all the documents in the collection, thus it does not insert
a new document and instead updates all existing.
Upvotes: 3
Reputation: 50406
I call false on this:
Here is the code listing to prove it, if your own code differs then this should be a guide:
var async = require('async'),
mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient;
MongoClient.connect('mongodb://localhost/test',function(err,db) {
if (err) throw err;
var collection = db.collection('bifftest');
async.eachSeries(
["Biff","Buff"],
function(name,callback) {
collection.update({},{ "name": name },{ "upsert": true },callback);
},
function(err) {
if (err) throw err;
collection.find({}).toArray(function(err,results) {
if (err) throw err;
console.log(results);
});
}
);
});
Returns:
[ { _id: 55b8992dcc8638610dca2e7c, name: 'Buff' } ]
Just as expected.
Upvotes: 3