dzm
dzm

Reputation: 23574

MongoDB bulk operator, insert if not exists

I'm using the MongoDB bulk operation to insert documents.

What I'd like to do is insert, only if no document is found - I don't want to update if it is found (i.e., upsert).

Any ideas how to do this?

However, even in this case:

var obj = {
 item: 'test'
}

bulk.find({ item: {$ne : obj.item}}).upsert().updateOne(obj);
bulk.execute();

This doesn't seem to actually insert anything if not found.

EDIT:

I wanted to update this to clarify a bit more.

There are two operations I'm trying to perform, using bulk api, one is to update and one is to insert.

The document looks like this:

{
  item: 'test',
  categories: [{
     name: 'one',
     attr: 'two'
  }]
}

What I'd like to do is if the item value is not found, then insert the obj. However, if it is found, then if categories.name is not found, $push the category object to the categories array. If the document is found and the category exists, do nothing.

Upvotes: 10

Views: 9031

Answers (2)

chridam
chridam

Reputation: 103445

What you'd want is to maintain the same update operation but change the query. From the documentation:

Bulk.find(<query>).upsert().update(<update>); Bulk.find(<query>).upsert().updateOne(<update>); Bulk.find(<query>).upsert().replaceOne(<replacement>);

With the upsert option set to true, if no matching documents exist for the Bulk.find() condition, then the update or the replacement operation performs an insert. If a matching document does exist, then the update or replacement operation performs the specified update or replacement.

Change the query to look for documents that satisfy the condition:

var obj = { item: 'test' };

bulk.find(obj).upsert().updateOne({ $setOnInsert: obj });
bulk.execute();

In the above, if the a matching document does exist, then the update with $setOnInsert does nothing as the update operation does not result in an insert, having found a document that matches the query.

Upvotes: 17

DurgaDatta
DurgaDatta

Reputation: 4170

you can do this:

db.collection.update(query, update, {upsert: true})

Example from official doc:

db.people.update(
   { name: "Andy" },
   {
      name: "Andy",
      rating: 1,
      score: 1
   },
   { upsert: true }
)

Upvotes: 0

Related Questions