Reputation: 823
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:
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
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:
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$unset
followed by $pullAll
to remove all null
'sUpvotes: 0
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