Search code examples
c#mongodbmongodb-.net-driver

Using C# MongoDB to convert Int to String?


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")

Solution

  • 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"
        }}
    ])