elemMatch 搜索子文档数组

elemMatch search on array of subdocument

如何在 SubDocument 数组上使用 elemMatch 进行搜索?我有一个名为 ReportCollection 的文档,其中包含以下元素:-

/* 0 */
{
    "_id" : ObjectId("5507bfc435e9470c9aaaa2ac"),
    "owner" : ObjectId("5507bfc31e14d78e177ceebd"),
    "reports" : {
        "xReport" : [ 
            {
                "name" : "xReport",
                "parameters" : {
                    "x" : {
                        "dateTime" : "2015-03-11T18:30:00.000Z",
                        "unit" : 1,
                        "value" : 102
                    }
                },
                "createdBy" : ObjectId("5507bfc31e14d78e177ceebd"),
                "modifiedBy" : ObjectId("5507bfc31e14d78e177ceebd"),
                "_id" : ObjectId("5507bfc41e14d78e177ceebf")
            }
        ]
    }
}

我得到 reports.xReport[]._id 作为搜索参数。

我的以下尝试失败了:-

  db.reports.find ({ {owner: ObjectId("5507afd3d54bae3513c185cb")}, 
    { 'reports.xReport': {$elemMatch: {_id: ObjectId("5507afd3d54bae3513c185cd") }}} } )

您似乎正在尝试将您应该在查询中执行的工作放入 "projection" 中。相反,您的声明应该更像这样:

db.reports.find(
    {
        "owner": ObjectId("5507bfc31e14d78e177ceebd"),
        "reports.xReport._id": ObjectId("5507bfc41e14d78e177ceebf")
    },
    { "reports.xReport.$": 1 }
)

所以 "query" 完成匹配数组位置的工作,而 "projection" 只是在匹配中使用该位置。

另请注意,您永远不需要 $elemMatch 与单个字段进行匹配。只有当条件中需要多个字段时,才需要使用它来匹配特定的"element"。

出于同样的原因,那也应该在 "query" 语句中。

$elemMatch 在其投影形式中不能通过点分符号与子文档字段一起使用。