Search code examples
c#mongodbmongodb-.net-driver

c# mongodb Find and remove one element from an array selected among several documents


I'm a newbie in a document-oriented database in general and in MongoDB in particular.

This database was created by me: a collection of several disjoint segments containing integers.

I'd like to take one item in accordance with some conditions and remove it from the document.

For example, I tried to take the item with conditions:

  1. from [-105; 17]
  2. not zero
  3. contains in {-104, -97, -5, 0, 5}

like this

var db          = client.GetDatabase("mongodbPOC");
var collection  = db.GetCollection<Document>("Int");
var contains    = new List<int> { -104, -97, -5, 0, 5 };
var result      = collection.AsQueryable()
                            .Where(document => 17 >= document.Min && -105 <= document.Max)
                            .SelectMany(document => document.Values)
                            .First(val => val != 0 && contains.Contains(val));

and find it again for remove, but I sure that exists a more profitable way to do that.


Solution

  • For remove finding a solution was not easy, but they helped me on the MongoDB forum in slack. To solve this problem there are two ways:

    1. using agg expressions in 4.2 for values where the position is known or unknown(Asya's answer): https://jira.mongodb.org/browse/SERVER-1014?focusedCommentId=2305681&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-2305681
    2. using $unset followed by $pullAll to remove all null's