1

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

xxdefaultxx
  • 175
  • 1
  • 12

1 Answers1

0

This is my very dirty workaround for the moment... Hoping somebody can still point me towards a better solution.

public virtual async Task<UpdateResult> AddEntryToArrayAsync<X>(string address, string id, X el)
    {
        try
        {
            var update = Builders<BsonDocument>.Update.Push(address, el);
            return await Collection.UpdateOneAsync(IdFilter(id), update);
        }
        catch(MongoWriteException e)
        {
            if (e.WriteConcernError == null)
            {
                var insert = Builders<BsonDocument>.Update.Set(address, new List<X> { el });
                return await Collection.UpdateOneAsync(IdFilter(id), insert);
            }
            throw e;
        }
    }
xxdefaultxx
  • 175
  • 1
  • 12
  • It's not working for Threading system ( it's not thread safe ), First data is replace by other date when some parallel coll execute and create an exception for these. – Kamruzzaman Jun 21 '20 at 03:53