[CSHARP-364] FindAndModify throws InvalidOperationException if upsert is true and query is null and collection is empty Created: 12/Dec/11  Updated: 02/Apr/15  Resolved: 29/Dec/11

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 1.3.1
Fix Version/s: 1.4

Type: Bug Priority: Minor - P4
Reporter: Gordon ML Assignee: Robert Stam
Resolution: Done Votes: 0
Labels: update
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

When performing an upsert to increment a counter value, as follows:

MongoDatabase database = MongoDatabase.Create("mongodb://localhost/test");
database.GetCollection("test").FindAndModify(null, SortBy.Null, Update.Inc("Counter", 1), true, true)

FindAndModify throws the following exception only when the collection is empty

System.InvalidOperationException
Command 'findAndModify' failed: exception: upsert mode requires query field (response:

{ "errmsg" : "exception: upsert mode requires query field", "code" : 13330, "ok" : 0.0 }

)

This is inconsistent behaviour: no exception is thrown if the document exists (works as expected); and the mongo shell allows the same command in javascript.



 Comments   
Comment by Robert Stam [ 13/Dec/11 ]

I guess you could open a server side JIRA if you felt strongly about the behavior one way or the other.

The C# driver is simply relaying whatever error (if any) the server returned.

Comment by Gordon ML [ 13/Dec/11 ]

Ahh yes, I don't know what I was doing different last night, it was a late one. However, it still seems like inconsistent behaviour to me: I thought that one of the great advantages of Mongo was that it doesn't matter if your collections don't exist yet, but in this case the error is only thrown if the collection doesn't exist/is empty. Also, it seems that you can put pretty much any query you like in there and it will work on an empty collection. For example, the following will work on an empty collection:

> db.test.findAndModify({
... query : { $eq : { Anything : 1 } },
... sort : { },
... update : { $inc : { Counter : 1 } },
... new : true,
... upsert : true
... })

Seems like the requirement for a query doesn't make a lot of sense (outwardly at least). Also the query itself doesn't make much sense because it isn't finding a row with Anything==1, but still manages to update the database.

Comment by Robert Stam [ 12/Dec/11 ]

I get the same exception when I run the query on an empty collection in the shell:

> db.test.findAndModify({
... query : null,
... sort : { },
... update : { $inc : { Counter : 1 } },
... new : true,
... upsert : true
... })
Mon Dec 12 17:47:09 uncaught exception: findAndModifyFailed failed: "exception: upsert mode requires query field"
>

Generated at Wed Feb 07 21:36:36 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.