c# - 如何在 MongoDb 和 C# 中编写多键查询?

标签 c# mongodb mongodb-.net-driver

在我们的 Mongo 数据库中,我们有一个由“StoreId”和“ItemId”索引的集合。以下查询返回“In”列表中包含的所有产品商店组合(总共 9 个文档)。

var productQuery = Query.In("ItemId", new BsonArray(new List<int> {1, 2, 3}));
var storeQuery = Query.In("StoreId", new BsonArray(new List<int> {1, 2, 3}));
var queryToBringNineDocuments = Query.And(productQuery, storeQuery);

如何编写一个查询,通过以下项目存储元组列表中的键返回文档?

var neededProductStores = new List<Tuple<int, int>>
{
    new Tuple<int, int>(1, 2),
    new Tuple<int, int>(1, 3),
    new Tuple<int, int>(2, 1),
    new Tuple<int, int>(3, 2)
};

var queryToBringFourDocuments = ?;

最佳答案

在我看来,目前只有一种方法——创建一个包含 id 和查询的额外字段

因此,在存储到数据库的 C# 类中,您可以拥有:

public string ProductStoreId 
{
  get 
  {
     return string.Format("{0}_{1}",ItemId, StoreId);
  }
  set { } //empty set means that it will be stored to database
}

那么您的查询将是:

var query = Query.In("ProductStoreId", new BsonArray(new List<string> {"1_2", "1_3",.. }));

关于c# - 如何在 MongoDb 和 C# 中编写多键查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9704513/

相关文章:

c# - Oracle触发器——从子表到父表

windows - mongodb - 数据库未连接

c# - 服务器实例不再连接。 MongoDB C# 驱动程序 1.3.1

c# - 如何在不同线程中处理视频帧(C#)

c# - 存储过程和 SqlCommand 超时

c# SpecFlow BeforeScenario 钩子(Hook)

python - 动态更新 mongodb

mongodb - 您如何解释 MongoDB 中的不同查询?

c# - 数据库从 RavenDB 迁移到 MongoDB

c# - 使用 MongoDB C# 驱动程序在嵌套数组上使用过滤器生成器进行查询