如何将这个Mongo Shell脚本转换为MongoDB C#驱动程序?var myItems = []var myCursor = db.Tickets.aggregate([{ $match : { TicketProjectID : 49 } },{ $project: { TicketProjectID:1, TicketID:1, concatValue: ...
如何将这个Mongo Shell脚本转换为MongoDB C#驱动程序?
var myItems = []
var myCursor = db.Tickets.aggregate(
[
{ $match : { TicketProjectID : 49 } },
{ $project: { TicketProjectID:1, TicketID:1, concatValue: { $concat: [ "$Status", " - ", "$Name" ] } } }
// I will have a list of fields that I need to concatenate at run time. So C# query should support concatenation for "N" number of fields at run-time.
//{ $group: { _id: null, count: { $sum: 1 } } }
],
{ allowDiskUse: true }
)
//This seems like a ugly performance approach when we are working against 100k results with above match
while (myCursor.hasNext()) {
var item = myCursor.next();
if(item.concatValue.search(/mysearchkey/i) > -1)
{
myItems.push(item.TicketID)
}
}
myItems
或者有更好的方法在连接投影中进行字符串搜索而不是游标中的foreach,因为一些quires可能获得50k记录.
这是我到目前为止所尝试的,(不使用聚合)
注意:修改此代码以适应公共Q& A站点.所以请将此视为伪代码
var tickets = ticketsCollection.FindSync(filter).ToList();
string concatinatedValue = string.Empty;
foreach (var ticket in tickets)
{
foreach (var field in customFieldsForThisProject)
concatinatedValue += ticket[field.Replace(" ", "_")];
if(concatinatedValue.StripHtml().contains("MysearchWord"))
{
TikectIdList.Add(ticket["TicketID"])
}
}
解决方法:
根据给定的评论编辑
如果你可以使用AsQueryable(),你可以得到这样的值:
var dbResult = from ticket in ticketsCollection.AsQueryable()
where ticket.TicketProjectID == 49
select new
{
TicketProjectID = ticket.TicketProjectID,
TicketID = ticket.TicketID,
ConcatValue = ticket.Status + " - " + ticket.Name
};
而且以后你可以这样做:
var result = from dbr in dbResult
where dbr.ConcatValue.Contains("something") //or
where dbr.ConcatValue.StartsWith("something")//or you can use regex
select dbr;
Note: For some reason both
Status
andName
properties from typeTicket
need to be of a typeString
for concatenation to work since mongo driver won’t recognize the call toToString()
from some other type.
如果要从其他类型连接属性,可以将它们与db分开,而不是在本地连接它们.
请注意,我对mongo shell不太好,我可以搞砸一些东西,但你可以看到你可以去哪种方式
或者,您可以像这样编写shell命令并将其放在一个字符串中:
var command = @"db.Tickets.aggregate(
[
{ $project: { TicketProjectID:1, TicketID:1, concatValue: { $concat: [ "$Status", " - ", "$Name" ] } } },
{ $match : { TicketProjectId : 49, concatValue : { $regex : /mysearchkey/i } } }
],
{ allowDiskUse : true }
);";
然后使用MongoDatabase中的RunCommandAsync方法在c#中执行它.
var result = await mongoDatabase.RunCommandAsync<BsonDocument>(BsonDocument.Parse(command));
本文标题为:MongoDB聚合Shell脚本到MongoC#Driver
基础教程推荐
- 利用C#开发浏览器扩展的全过程记录 2023-04-22
- C#获取某路径文件夹中全部图片或其它指定格式的文件名的实例方法 2023-02-02
- c#中LINQ的基本用法(三) 2023-05-31
- c# – Windows安装程序中的通用应用程序数据路径 2023-09-18
- C#实现记事本查找与替换功能 2023-01-22
- C#项目中跨文件调用公共类的实例方法 2023-01-27
- .netcore3.1项目发布到centos docker 2023-09-26
- .Net Core 项目发布到Linux - CentOS 7(一) 2023-09-26
- 如何使用Dapper处理多个结果集与多重映射实例教程 2022-12-31
- 在WPF中使用Interaction.Triggers 2023-06-20