【问题标题】:Query all documents in the collection to find if certain document contains value查询集合中的所有文档以查找某个文档是否包含值
【发布时间】:2022-01-17 15:39:10
【问题描述】:

假设我在 mongodb 集合中有数千个文档。每个随机文档都包含具有两个属性(ownerId、ownerRef)的对象 ownerData

{
   "_id": {....},
   "name": "abc",
   "ownersData": { "ownerId":"1", "ownerRef":"qwer" }
   
}

使用某些文档包含某些 ownerRef 值的信息来查询所有文档的最快方法应该是什么

【问题讨论】:

  • 在 ownerData.ownerRef 上创建索引

标签: c# .net mongodb


【解决方案1】:

假设您有代表数据库中数据的 C# 对象,您可以使用 linq 实现此目的。

public IEnumerable<Document>? GetDocumentByOwnerRef(string ownerReference)
 => dbContext.Documents.Where(d =>
      d.ownerData is not null && d.ownersData.ownerRef.Equals(ownerReference)
    ).ToList();

编辑:正如@SJFJ 在 cmets 中正确指出的那样;虽然这确实有效,但它扫描您的整个收藏,这是一个非常漫长的过程。在 mongodb 的 ownerRef 列上创建索引将节省性能和加载时间。

【讨论】:

  • 创建索引以防止完整的集合扫描很重要
  • @SJFJ 欢呼,更新我的答案
猜你喜欢
  • 1970-01-01
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
  • 2018-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
相关资源
最近更新 更多