c# - 使用 Mongodb-CSharp Driver 调用函数

标签 c# linq mongodb

目前,我在为 MongoDb 开发 Csharp Driver LinQ,但在实现类似于在 MongoDb 上调用存储函数的方法时遇到了问题。其实我知道MongoDB没有存储过程机制。我需要有人提出建议或解决方案来解决这个问题。重要的是数据将以某种方式在 mongodb 中完成,而不是在内存中完成。例如,我想返回一个列表,其中包含通过自定义方法实现的过滤条件。此方法基于字段依赖性进行计算。

一个例子在内存中完成。

var list = collection.AsQueryable<Rule>().ToList();    
var result = list.Where(x => x.Active && CalcMethod(x.Rule)> 5);

这里是自定义方法。

public static int CalcMethod(Rule rule)
{           
    if(rule.Active)   
        // bypass check null 
        return rule.Weight.Unit * rule.Weight.Value;
    else
       // return something here
}

CalcMethod 方法类似于 SQL Server 中的函数。 无论我们是否可以使用 MongoDb 或其他工具来做到这一点,都希望我们可以注入(inject)一种方法来计算数据和过滤,而无需在内存中完成。 我们将不胜感激。

最佳答案

桑纳, 我认为您可以为此使用聚合(或 MapReduce 来处理复杂的事情)。即:

async void Main()
{

  var client = new MongoClient("mongodb://localhost");
  var db = client.GetDatabase("TestSPLike");
  var col = db.GetCollection<Rule>("rules"); 

  await client.DropDatabaseAsync("TestSPLike"); // recreate if exists
  await InsertSampleData(col); // save some sample data

  var data = await col.Find( new BsonDocument() ).ToListAsync();
  //data.Dump("All - initial");

/*  
  db.rules.aggregate(
   [
     { $match: 
        {
         "Active":true
        }
     }, 
     { $project: 
        { 
         Name: 1, 
         Active: 1, 
         Weight:1, 
         Produce: { $multiply: [ "$Weight.Unit", "$Weight.Value" ] }
        } 
     },
     { $match: 
        {
          Produce: {"$gt":5}
        }
     }
   ]
)
*/ 

var aggregate = col.Aggregate()
  .Match(new BsonDocument{ {"Active", true} })
  .Project( new BsonDocument {
      {"Name", 1}, 
      {"Active", 1}, 
      {"Weight",1}, 
      {"Produce", 
         new BsonDocument{
           { "$multiply", new BsonArray{"$Weight.Unit", "$Weight.Value"} }
        }} 
  } )
  .Match( new BsonDocument { 
       { "Produce", 
          new BsonDocument{ {"$gt",5} } 
          }
          })
  .Project( new BsonDocument {
      {"Name", 1}, 
      {"Active", 1}, 
      {"Weight",1} 
      } );
  var result = await aggregate.ToListAsync();
  //result.Dump();
}

private async Task InsertSampleData(IMongoCollection<Rule> col)
{
 var data = new List<Rule>() {
   new Rule { Name="Rule1", Active = true, Weight = new Weight { Unit=1, Value=10} },
   new Rule { Name="Rule2", Active = false, Weight = new Weight { Unit=2, Value=3} },
   new Rule { Name="Rule3", Active = true, Weight = new Weight { Unit=1, Value=4} },
   new Rule { Name="Rule4", Active = true, Weight = new Weight { Unit=2, Value=2} },
   new Rule { Name="Rule5", Active = false, Weight = new Weight { Unit=1, Value=5} },
   new Rule { Name="Rule6", Active = true, Weight = new Weight { Unit=2, Value=4} },
 };

 await col.InsertManyAsync( data,new InsertManyOptions{ IsOrdered=true});
}

public class Weight
{
  public int Unit { get; set; }
  public int Value { get; set; }
}

public class Rule
{
  public ObjectId _id { get; set; }
  public string Name { get; set; }
  public bool Active { get; set; }
  public Weight Weight { get; set; }
}

关于c# - 使用 Mongodb-CSharp Driver 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31676453/

相关文章:

mongodb - 使用 angular、express 和 mongodb 的 gridfs 上传文件

spring - Spring Mongodb 中的过滤器搜索查询

java - 如何从 unix 终端运行简单的 MongoDB java 程序

c# - .Net Core Integration TestServer 与 Generic IHostBuilder

C# Dictionary 并发添加或修改仅针对不同的键,是否需要ConcurrentDictionary?

c# - Assembly.LoadFrom 在包含 MFC 的 cpp/CLI DLL 上失败

c# - 面向初学者的 LINQ

c# - 查找与给定抵达/出发日期冲突的预订

c# - 如何从 msbuild 获取构建日志?

linq - 无法使 GroupJoin 工作。 NavigationExpandingExpressionVisitor 异常