2

I'm using C# MongoDb.Driver(2.10) to get a document from a collection :

MongoClient dbClient = new 
MongoClient("mongodb://***");
IMongoDatabase db = dbClient.GetDatabase("***");
var collection = db.GetCollection<BsonDocument>("***");
Console.WriteLine( collection.Find(Builders<BsonDocument>.Filter.Empty).First());

This does work and emits this :

enter image description here

So everything is OK.

But now I want to try to filter where lockPolicyId.ToString()=="1" .(As a string , not as a number)

So I've tried :

var filter= Builders<BsonDocument>.Filter.Where(a=>a["lockPolicyId"].AsString=="1");
var t=collection.Find( filter ).First() ;
Console.Writeline(t);

Which shows this error :

The operands for operator 'Equal' do not match the parameters of method 'op_Equality'.

I've also tried:

 var filter= Builders<BsonDocument>.Filter.Where(a=>a["lockPolicyId"].ToString()=="1");

And got this error:

{document}{lockPolicyId}.ToString() is not supported.

Now, I do understand why it's happening ( Int and not String).

But still

Question:

How can I filter by the ToString value?

In other words, to make this line works:

Builders<BsonDocument>.Filter.Where(a=>a["lockPolicyId"].AsString=="1")
3
  • The column must be another class. When you type the period what options are you given? Commented Jan 19, 2020 at 11:11
  • @jdweng i.imgur.com/X3xQDqE.jpg Commented Jan 19, 2020 at 11:21
  • It is a MongoDB object. Those selections are not a standard Net Library type. Commented Jan 19, 2020 at 14:53

1 Answer 1

2

Not possible.

MongoDB C# driver interprets a=>a["lockPolicyId"]==1 as {lockPolicyId: {"$eq" : "1"}}.

When you try a=>a["lockPolicyId"].AsString=="1", it can't be interpreted into MongoDB syntax... (such query {{$toString:"lockPolicyId"} : "1"} is invalid)


MongoDB .find method has exception with $where operator:

db.collection.find({"$where": "this.lockPolicyId.toString() == '1'"})

But you need to write such queries manually (can't be written by Predicate interface). Note: It's very slow

MongoDB offers aggregate command to perform unusual queries. You need to define query pipeline. If you use $toString operator in the 1st stage and then apply matching criteria in the 2nd one, it will work:

db.collection.aggregate([
    {$addFields:{
        lockPolicyId : {$toString:"$lockPolicyId"}
    }},
    {$match:{
        lockPolicyId : "1"
    }}
])
Sign up to request clarification or add additional context in comments.

1 Comment

So what is AsString is there for ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.