Delete element from string array in mongodb

Asked

Viewed 70 times

0

Hello.

I want to delete an element from a string array, in this case it is the Profiles array, which is present in the Person Document.

This in an application developed in . net and with mongodb driver.

Example of a document in the collection:

{"_id":{"$oid":"5e285ff7ac033a913ca37a0c"},"PersonId":{"$numberInt":"7"},"Profiles":["profile1","profile2","profile3"],"CreatedDate":{"$date":{"$numberLong":"1579703399301"}},"UpdatedDate":{"$date":{"$numberLong":"1579703399301"}}}

And the code to remove from the array in c#:

  var update = Builders<Person>.Update.PullFilter(
        c => c.Profiles,
        s => s == "profile1");

    await this.DBset.FindOneAndUpdateAsync(c => c.PersonId == personId, update).ConfigureAwait(false);

The following error is being returned:

    System.InvalidOperationException: '{document} is not supported.'
MongoDB.Driver.Linq.Translators.PredicateTranslator.GetFieldExpression(System.Linq.Expressions.Expression)
    MongoDB.Driver.Linq.Translators.PredicateTranslator.TranslateComparison(System.Linq.Expressions.Expression, System.Linq.Expressions.ExpressionType, System.Linq.Expressions.ConstantExpression)
    MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(System.Linq.Expressions.Expression)
    MongoDB.Driver.Linq.Translators.PredicateTranslator.Translate(System.Linq.Expressions.Expression, MongoDB.Bson.Serialization.IBsonSerializerRegistry)
    MongoDB.Driver.MongoCollectionImpl<TDocument>.UsingImplicitSessionAsync<TResult>(System.Func<MongoDB.Driver.IClientSessionHandle, System.Threading.Tasks.Task<TResult>>, System.Threading.CancellationToken)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()

Any idea what it might be?

Thank you.

1 answer

1


Replacing the PullFilter for Pull should result.

var update = Builders<Person>.Update.Pull(c => c.Profiles, "profile1");

await this.DBset.FindOneAndUpdateAsync(c => c.PersonId == personId, update).ConfigureAwait(false);

PS: If you don’t need to get the result of the query, you can also change FindOneAndUpdateAsync for UpdateOneAsync.

  • Thank you! It worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.