Mongodb查询基于2个字段进行匹配

时间:2018-12-17 10:09:39

标签: c# mongodb mongodb-query

让我先举一个例子,

{
 $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:7recipient:1的组合是无效的,只有sender:7recipient:2recipient:3的组合才有效有效。

有什么方法可以简化C#中的上述查询?

1 个答案:

答案 0 :(得分:0)

如果您想编写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) );