Paritosh
Paritosh

Reputation: 83

FindAndModify missing in mongodb C# driver

I am using Mongodb shell 3.2.4 and C# driver 2.2.3. I have even installed legacy driver 2.2.3 but still facing following problem.

I want to use AutoIncremented value for one of my field i.e eventID so I am trying to use FindAndModify but I cannot seem to find it.

_client = new MongoClient();
_database = _client.GetDatabase("users");
var counters = _database.GetCollection<BsonDocument>("counters");
var counterQuery = Query.EQ("_id", "eventId");

var findAndModifyResult = counters.FindAndModify(
      new FindAndModifyArgs()
      {
          Query = counterQuery,
          Update = Update.Set("web", "testweb")
     });

But I get following error:

Error   2   'MongoDB.Driver.IMongoCollection<MongoDB.Bson.BsonDocument>' does not contain a definition for 'FindAndModify' and no extension method 'FindAndModify' accepting a first argument of type 'MongoDB.Driver.IMongoCollection<MongoDB.Bson.BsonDocument>' could be found (are you missing a using directive or an assembly reference?)

Attaching screenshot
enter image description here

Upvotes: 3

Views: 4253

Answers (1)

Kevin Blake
Kevin Blake

Reputation: 444

In the new 2.0 driver, this is now called FindOneAndUpdate.

You have a mix of the old legacy, and new format in your question - Query.EQ is also from the legacy driver - so I suggest removing that legacy driver as the first step.

Then you should be able to get what you need by using the Builders, for example:

var _client = new MongoClient();
var _database = _client.GetDatabase("users");
var counters = _database.GetCollection<BsonDocument>("counters");
var counterQuery = Builders<BsonDocument>.Filter.Eq("_id", "eventId");

var findAndModifyResult = counters.FindOneAndUpdate(counterQuery,
              Builders<BsonDocument>.Update.Set("web", "testweb"));

Upvotes: 10

Related Questions