[英]Using C# MongoDB to convert Int to String?
I'm using C# MongoDb.Driver
(2.10) to get a document from a collection :我正在使用 C#
MongoDb.Driver
(2.10) 从集合中获取文档:
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 :这确实有效并发出:
So everything is OK.所以一切正常。
But now I want to try to filter where lockPolicyId.ToString()=="1"
.( As a string , not as a number )但现在我想尝试过滤 where
lockPolicyId.ToString()=="1"
.(作为字符串,而不是数字)
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'.
运算符“Equal”的操作数与方法“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.
不支持 {document}{lockPolicyId}.ToString()。
Now, I do understand why it's happening ( Int and not String).现在,我明白为什么会发生这种情况(Int 而不是 String)。
But still但还是
Question:题:
How can I filter by the ToString value?如何按 ToString 值过滤?
In other words, to make this line works:换句话说,要使这条线起作用:
Builders<BsonDocument>.Filter.Where(a=>a["lockPolicyId"].AsString=="1")
MongoDB C# driver interprets a=>a["lockPolicyId"]==1
as {lockPolicyId: {"$eq" : "1"}}
. MongoDB C# 驱动程序将
a=>a["lockPolicyId"]==1
为{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)当您尝试
a=>a["lockPolicyId"].AsString=="1"
,它无法解释为 MongoDB 语法......(这样的查询{{$toString:"lockPolicyId"} : "1"}
是无效的)
MongoDB .find
method has exception with $where
operator: MongoDB
.find
方法有$where
操作符的异常:
db.collection.find({"$where": "this.lockPolicyId.toString() == '1'"})
But you need to write such queries manually (can't be written by Predicate
interface).但是您需要手动编写此类查询(不能通过
Predicate
接口编写)。 Note: It's very slow注意:它很慢
MongoDB offers aggregate
command to perform unusual queries. MongoDB 提供
aggregate
命令来执行异常查询。 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:如果您在第一阶段使用
$toString
运算符,然后在第二阶段应用匹配条件,它将起作用:
db.collection.aggregate([
{$addFields:{
lockPolicyId : {$toString:"$lockPolicyId"}
}},
{$match:{
lockPolicyId : "1"
}}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.