When using upsert operation with a filter statement that contains .Count, the following error is thrown:
Unhandled exception. MongoDB.Driver.MongoWriteException: A write operation resulted in an error. WriteError: { Category : "Uncategorized", Code : 224, Message : "$expr is not allowed in the query predicate for an upsert" }. ---> MongoDB.Driver.MongoBulkWriteException`1[MongoDBUpdateExample.DbTargetRecord]: A bulk write operation resulted in one or more errors. WriteErrors: [ { Category : "Uncategorized", Code : 224, Message : "$expr is not allowed in the query predicate for an upsert" } ].
This does not happen on versions below 2.19, such as 2.18.
The following code reproduces the issue. It works without issues for versions < 2.19.0 and starts throwing the error for any version >= 2.19.0.
using MongoDB.Driver; using System; using System.Threading.Tasks; namespace MongoDBUpdateExample { class Program { static async Task Main(string[] args) { // Initialize MongoDB client and get the collection var client = new MongoClient("connection_string"); // Replace with your MongoDB connection string var database = client.GetDatabase("db"); // Replace with your database name var collection = database.GetCollection<DbTargetRecord>("collection"); // Replace with your collection name FilterDefinition<DbTargetRecord> filter = Builders<DbTargetRecord>.Filter.Where( x => x._id == "1" && x.DistinctAnchors.Count <= 3 ); UpdateDefinition<DbTargetRecord> updateDefinition = Builders<DbTargetRecord>.Update.Set(z => z.LastUpdateTime, DateTime.UtcNow); UpdateResult result = await collection.UpdateOneAsync(filter, updateDefinition, new UpdateOptions() { IsUpsert = true }); } } public class DbTargetRecord { public string _id { get; set; } public List<string> DistinctAnchors { get; set; } public DateTime LastUpdateTime { get; set; } } public class TargetAnchor { public string Target { get; set; } public string Anchor { get; set; } } }