【问题标题】:MongodDB retrieve a subdocument by the property nameMongodB 通过属性名称检索子文档
【发布时间】:2014-02-20 14:44:54
【问题描述】:

我的文档如下所示:

{ "entity_id" : 2,
  "features" :
  [
     { "10" : "name" },
     { "20" : "description" },
     ... ,
     { "90" : "availability" }
  ]
 }

我想知道两件事:"entity_id" (2) 的值,以及 "features" 数组的元素之一中的属性值,以便仅检索子文档

{ "20" : "description" }

在一个查询中。非常感谢!

【问题讨论】:

  • .find({'features.20':{$exists:true}})
  • 这将给出整个文档。我只想要属性为 20 的元素文档
  • @portforwardpodcast 您是否试图指出“mongodb 中的任何查询始终返回根文档”,如链接中问题的答案所述?如果是这样,另一个答案指出这个限制在 2.2.x 中消失了
  • 聚合框架改变了您当前可以做的事情的性质,并且不能很好地替代仅返回文档的一部分。由于它旨在“聚合”,因此您会发现一般用法对于非聚合类型的查询很麻烦。

标签: mongodb subdocument


【解决方案1】:

如果您只想获取整个文档的一部分,请使用所谓的Projection operators

请看下面的例子:

> db.collection.find().pretty()
{
    "_id" : ObjectId("52e861617acb7ce761e64a93"),
    "entity_id" : 2,
    "features" : [
        {
            "10" : "name"
        },
        {
            "20" : "description"
        },
        {
            "90" : "availability"
        }
    ]
}

在 find() 中指定投影运算符,如下所示:

> db.collection.find({},{ features : { $elemMatch : { 20 : { $exists: true } }}}).pretty()
{
    "_id" : ObjectId("52e861617acb7ce761e64a93"),
    "features" : [
        {
            "20" : "description"
        }
    ]
}

> db.collection.find({},{ entity_id : 1, features : { $elemMatch : { 20 : { $exists: true } }}}).pretty()
{
    "_id" : ObjectId("52e861617acb7ce761e64a93"),
    "entity_id" : 2,
    "features" : [
        {
            "20" : "description"
        }
    ]
}
> db.collection.find({},{ _id : 0, entity_id : 1, features : { $elemMatch : { 20 : { $exists: true } }}}).pretty()
{ "entity_id" : 2, "features" : [ { "20" : "description" } ] }

$elemMatch 用于投影自 2.2 版起在 MongoDB 中可用。

希望它能解决你的问题。

【讨论】:

  • 这些都没有返回我正在寻找的东西。我错过了什么吗?你测试过吗?
  • 也许你应该考虑在你的问题中准确包含你所期望的输出,如果这不是你的意思,因为似乎有一个混乱?我将 MongoDB 控制台的输出与查询一起粘贴给您,所以“我是否测试了这些查询”这个问题有点荒谬。
  • 来自我的问题:在一个查询中检索文档 { "20" : "description" }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-27
  • 2020-11-27
  • 2015-05-25
  • 2016-02-16
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多