C # mongoDb 2.0 Does not exist in the dictionary

I want to update a collection that contains only some Id and an objectId dictionary for objectId.

public class ME_BlaBla { [BsonId] public ObjectId MyId; public Dictionary<ObjectId, ObjectId> IdsToOtherIds; } 

I'm sorry if my names are not informative, I cannot exchange the 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, I'm trying to filter out the MyId field, but when I want to insert data there, I do not want duplication of any type, not in Keys or in Values

The whole idea is that the update should be atomic and verify that none of the identifiers provided are in the dictionary.

I'm still trying to figure out how to use the Exists filter here, so this might be the answer.

TIA.

EDIT

I changed the code to something like this: (still not sure if it works well ... does not test its 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))); 
+6
source share
2 answers
 Builders<ME_BlaBla>.Filter.Not(Builders<ME_BlaBla>.Filter.Exists(t => t.IdsToOtherIds.Values, valueId)) 

This piece of code will not check if valueId exists in the Values property (which is a list of elements of type ObjectId ) of the Dictionary field (which you mean, I assume). Exists checks if the document contains a specific field; You can check if the dictionary or surname field is in your collection document.

If you need a unique value in your application, could you create a singleton class somewhere that will generate the next (and therefore unique) value of a specific sequence?

Your Dictionary is probably serialized as an array of documents, so if you need to check if a document exists in the collection, you need to use AnyIn (or some others) instead of Exists .

+1
source

You can see the nested list expression with such criteria,

https://docs.mongodb.org/manual/core/read-operations-introduction/

in your state you can use your dictionaries as 2 such criteria for combining,

https://docs.mongodb.org/manual/reference/operator/query/elemMatch/

Hooray!

0
source

All Articles