I want to update a collection which only contains some Id and a dictionary of objectId to objectId.
public class ME_BlaBla
{
[BsonId]
public ObjectId MyId;
public Dictionary<ObjectId, ObjectId> IdsToOtherIds;
}
Im sorry if my names aren't informative, I can't share real code =.
Now, I have this query:
var filter = Builders<ME_BlaBla>.Filter.And(
Builders<ME_BlaBla>.Filter.Eq(t => t.MyId, id),
Builders<ME_BlaBla>.Filter.Not(Builders<ME_BlaBla>.Filter.Exists(t => t.IdsToOtherIds.Values, valueId)),
Builders<ME_BlaBla>.Filter.Not(Builders<ME_BlaBla>.Filter.Exists(t => t.IdsToOtherIds.Keys, keyId)));
So, Im trying to filter by the MyId
field but when I want to insert data to there I don't want duplication of any kind, Not in the Keys
nor in the Values
The whole idea is that the updating must be atomic and check that neither of the provided ids are contained in the dictionary.
I'm still trying to understand how to use the Exists
filter here, so it might be the answer.
TIA.
EDIT
I changed the code to something like that: (still not sure its working well..cannot test it atm)
Builders<ME_BlaBla>.Filter.Not(Builders<ME_BlaBla>.Filter.ElemMatch(t => t.IdsToOtherIds, a => a.Key == keyId)),
Builders<ME_BlaBla>.Filter.Not(Builders<ME_BlaBla>.Filter.ElemMatch(t => t.IdsToOtherIds, a => a.Value == valueId)));
Builders<ME_BlaBla>.Filter.Not(Builders<ME_BlaBla>.Filter.Exists(t => t.IdsToOtherIds.Values, valueId))
This part of code won't check if valueId
value exists in the Values
property (which is a list of elements of type ObjectId
) of the field Dictionary
(that's what you meant, I guess). Exists
checks if the document contains certain field; you could check if document of your collection have a field "Dictionary" or "Surname".
If you need a unique value in your application, could you possibly create a singleton class somewhere which will generate next (and thus unique) value of certain sequence?
Your Dictionary
probably is serialized as array of documents, so if you need to check whether document already exist in the collection, you need to use AnyIn
(or some other) instead of Exists
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With