EgoPingvina
EgoPingvina

Reputation: 823

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.

Upvotes: 0

Views: 1678

Answers (2)

EgoPingvina
EgoPingvina

Reputation: 823

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

Upvotes: 0

user10613920
user10613920

Reputation:

To remove items from array in MongoDb, you need to use Pull or PullFilter, in your case, you need to use PullFilter, like this:

var filterPull = Builders<int>.Filter
                              .Where(x => x != 0 && contains.Contains(x));
var update = Builders<YourModel>.Update
                                .PullFilter(c => c.Values, filterPull);

Then create another filter for Min, Max condition, this filter is for your document and use Update Collection:

var filter = Builders<YourModel>.Filter
                                .Where(document => 17 >= document.Min && -105 <= document.Max);
Collection.UpdateManyAsync(filter, update);

Upvotes: 2

Related Questions