c# - 基于 2 个字段匹配的 Mongodb 查询
问题描述
我先举个例子,
{
$match: {
$or:[
{'sender':1, 'recipient':2},
{'sender':2, 'recipient':1},
{'sender':1, 'recipient':3},
{'sender':7, 'recipient':2},
{'sender':7, 'recipient':3} //goes on may be 20 or 30
]
}
}
我正在尝试根据发件人和收件人获取数据。如果发件人和收件人属于这种类别组合,我只选择该数据。
从上面的例子我可以说sender:7
and的组合recipient:1
是无效的,只有sender:7
and recipient:2
or的组合recipient:3
是有效的。
有什么方法可以简化上述查询C#
?
解决方案
如果您想编写 c# 查询,我建议您为此使用存储库,这将使您的事情变得更容易,您可以编写一些实体框架样式的查询
https://github.com/alexandre-spieser/mongodb-generic-repository
public class TestMongoRepository: BaseMongoRepository, IEmailMongoRepository
{
public TestMongoRepository(string connectionString, string databaseName) : base(connectionString, databaseName)
{
}
//public MongoRepository<T> Create<T>() where T:IEntity
//{
// return new MongoRepository<T>();
//}
}
}
public class Data: Document
{
public string Sender { get; set; }
public string Receiver{ get; set; }
}
那么您可以使用以下语法进行查询
var _yourRepository=new TestMongoRepository("connectionstring","database");
class Combination{
public int Sender{get;set;}
public int Receiver {get;set;}
}
var combinations=new List<Combination>{
new Combination{Sender=1, Receiver=5},
// add your other comibnaitons here
}
var data= _yourRepository.GetAll<Data>(e =>combinations.Any(c=>c.Sender=e.Sender && c.Receiver=e.Receiver) );
推荐阅读
- gremlin - 关闭 SessionClient 上的连接 - AWS Neptune
- python - Tkinter - 如何在函数之间切换列表?
- leaflet - 在 Leaflet 中显示 mbfiles
- c# - 如何在 .NET5 或 .Net6 中使用 UIAutomation
- ruby - 反正有没有调用多个结束语句
- regex - 忽略 Npp 正则表达式中的特定字符
- php - 如何将php变量中的第二个逗号与html中的mysql分开
- flutter - 在颤振仪表板中添加背景
- r - 如何在 R 的文本文件中保存非英文字符?
- linux - How to save FTP session logs in file in Linux