[SERVER-1182] Add $noop operation to update or another insert if not exist feature Created: 02/Jun/10  Updated: 07/Jul/10  Resolved: 07/Jul/10

Status: Closed
Project: Core Server
Component/s: Querying
Affects Version/s: 1.5.2
Fix Version/s: None

Type: Improvement Priority: Minor - P4
Reporter: Scott Hernandez (Inactive) Assignee: Eliot Horowitz (Inactive)
Resolution: Won't Fix Votes: 2
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Participants:

 Description   

Add a $noop operations so you can effectively do an insert if some criteria doesn't already exist.

db.coll.update({_id:25, name:"John"}, {$noop:1}, true, false)

This question came up in IRC and is the reason for this request: "I want to insert some data into a collection if and only if it doesn't exist already?"

This can be done with a query + insert but would be closer to the RDBMS version (which is wrapped in a transaction normally) using the syntax above (which is atomic).

I could also see this working by using a null second param for update (this is not currently allowed), but the $noop is clearer.



 Comments   
Comment by Eliot Horowitz (Inactive) [ 07/Jul/10 ]

Actually - this will work fine today

> db.foo.update(

{ a : 1 , b : 2 }

, { $set : {} } , true )

$set : {} === $noop

Comment by Dwight Merriman [ 07/Jul/10 ]

what's wrong with just doing an insert, and having it fail because of dup _id if the value is already there?

Comment by Erick Tryzelaar [ 01/Jul/10 ]

I got an implementation for this patch here: http://github.com/erickt/mongo.

Comment by Eliot Horowitz (Inactive) [ 22/Jun/10 ]

@erick yes

Comment by Erick Tryzelaar [ 22/Jun/10 ]

Just to be clear, is this what you are expecting?

> db.coll.find();
> db.coll.update({_id:25, name:"John"}, {$noop:1}, true, false);
> db.coll.find();
{_id:25, name:"John"}
> db.coll.update(

{name:"John"}

, {$noop:1}, true, false);
> db.coll.find();
{_id:25, name:"John"}

Comment by Scott Hernandez (Inactive) [ 02/Jun/10 ]

Understood, but that will replace the item at _id:5 with the document {_id:5, x:5 }. if the existing document already exists it will override it, or update it.

This could also be done with a insert() with values that are in a unique index but that has other issues since any component of the compound index that is missing a field could cause a violation to the uniqueness because missing fields result in a null value in the index.

What you have suggested does not satisfy the "insert only if missing" part of the problem.

Comment by Eliot Horowitz (Inactive) [ 02/Jun/10 ]

The canonical way to do this is

update(

{ _id : 5 }

,

{ x : 5 }

, true )

where the left side is the unique constraint

Generated at Thu Feb 08 02:56:18 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.