I am using the mongodb c# driver and attempting to insert an initialized array when the field is null, and push when an array already exists at the address ( at this stage I am just assuming an array exists at the address field if it is not null ).
I am using the below method which returns that a false positive that the value at the address is null and therefore keeps overwriting itself with a new array.
Could anyone point me to the correct way to query whether a null value exists at the address?
public virtual async Task<UpdateResult> AddEntryToArrayAsync<X>(string address, string id, X el)
{
var isNullQuery = Builders<BsonDocument>.Filter.Eq(address, BsonNull.Value) & IdFilter(id);
var isNullCount = await Collection.CountAsync(isNullQuery);
if (isNullCount > 0)
{
var insert = Builders<BsonDocument>.Update.Set(address, new List<X>() { el });
return await Collection.UpdateOneAsync(IdFilter(id), insert);
}
var update = Builders<BsonDocument>.Update.Push(address, el);
return await Collection.UpdateOneAsync(IdFilter(id), update);
}
protected static FilterDefinition<BsonDocument> IdFilter(string id)
{
return Builders<BsonDocument>.Filter.Eq("_id", id);
}
I am confident everything else working correctly as the correct address is being overwritten each time with the new init. array