[英]elemMatch search on array of 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") }}} } )
似乎您正在尝试将工作放入查询中应该执行的“投影”中。 相反,您的声明应更像这样:
db.reports.find(
{
"owner": ObjectId("5507bfc31e14d78e177ceebd"),
"reports.xReport._id": ObjectId("5507bfc41e14d78e177ceebf")
},
{ "reports.xReport.$": 1 }
)
因此,“查询”完成匹配数组位置的工作,而“投影”仅在匹配中使用该位置。
还要注意,您实际上并不需要$elemMatch
与单个字段进行匹配。 仅在条件中需要多个字段时,才需要使用它来匹配特定的“元素”。
同样,它也应该在“查询”语句中。
投影格式的$elemMatch
不能通过点分符号与子文档字段一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.