【问题标题】:$match operator for sub document field in MongoDbMongoDb中子文档字段的$match运算符
【发布时间】:2011-12-28 22:45:22
【问题描述】:

我正在尝试 MongoDB 的新管道查询,因此我尝试执行以下查询。

{
aggregate: 'Posts',
pipeline: [
    { $unwind: '$Comments'},
    { $match: {'$Comments.Owner': 'Harry' }},
    {$group: {
        '_id': '$Comments._id'
        }
     }
   ]
}

没有任何匹配的查询,所以返回空结果。我想问题可能出在 $match 命令上。我正在使用点符号匹配评论所有者,但不确定它是否完全正确。为什么此查询不返回 'Harry' 的所有者。我确定它存在于数据库中。

【问题讨论】:

  • 有什么想法或猜测吗?我可以在 Post 的“Title”属性上使用 $match 命令,所以我确信“$Comments.Owner”语法有问题。
  • 您能否在您的收藏中发布一些示例文档,以便更好地了解查询应该如何工作?谢谢。

标签: mongodb aggregation-framework


【解决方案1】:

您不要为 $match 字段名称使用 $ 前缀。

试试这个:

{
  aggregate: 'Posts',
  pipeline: [
    { $unwind: '$Comments'},
    { $match: {'Comments.Owner': 'Harry' }},
    { $group: {
      '_id': '$Comments._id'
    }}
  ]
}

【讨论】:

    【解决方案2】:

    我在使用 MongoDB 2.2 的聚合框架时遇到了同样的问题。

    $match 不适用于我的子文档(但我只是在学习 MongoDB,所以我可能会做错事)。

    我添加了额外的投影来删除子文档(在这种情况下为Comments):

    {
    aggregate: 'Posts',
    pipeline: [
        { $unwind: '$Comments'},
        { $project: {
          comment_id: "$Comments._id",
          comment_owner: "$Comments.Owner"
        }},
        { $match: {'$comment_Owner': 'Harry' }},
        {$group: {
            '_id': '$comment_id'
            }
         }
       ]
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2020-12-03
      相关资源
      最近更新 更多