【问题标题】:Is it possible retrieve only one specific field of a subdocument from an array?是否可以从数组中仅检索子文档的一个特定字段?
【发布时间】:2013-02-10 22:32:04
【问题描述】:

假设我在 MongoDB 集合上有以下文档结构:

{
  "Applications" : [{
      "JoinDate" : new Date("10/2/2013 18:06:30"),
      "Key" : "shtube",
      "Roles" : ["Administrator", "Moderator"]
    }],
  "Comment" : "Cool",
  "ConfirmationKey" : "981c69fe-6fff-47d6-bb82-3b5f1deeef25",
  "CreationDate" : new Date("8/2/2013 17:43:42"),
  ...
} 

如何使用 MongoCursor 的 SetFields() 方法仅检索“角色”字段(针对性能问题)?此时我只知道检索子文档并访问“角色”。但我不需要整个子文档信息。

【问题讨论】:

    标签: c# asp.net arrays mongodb projection


    【解决方案1】:

    您可以使用投影来使用点表示法(使用 shell)仅提取您想要的字段:

    db.myCollection.find({ "Applications.Roles" : { $exists: true } },
                 {  "Applications.Roles" : 1 })
    

    在上面的示例中,它只是返回包含 Applications.Roles 结构的文档。

    您可以阅读有关预测的更多信息here

    仅供参考:您无法使用 LINQ 从 C# 高效地进行投影。它在客户端本地进行投影。

    另一种选择是使用 $elemMatch(但是,在这种情况下,如果您不进行特定查询,它可能不适合您的需求)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 2023-03-05
      • 2014-06-08
      相关资源
      最近更新 更多