首页 > 解决方案 > 基于 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:7and的组合recipient:1是无效的,只有sender:7and recipient:2or的组合recipient:3是有效的。

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

标签: c#mongodbmongodb-query

解决方案


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

推荐阅读