Mongodb 对mongo多键复合查询执行和(带或不带mongoid)
我有以下格式的数据结构:Mongodb 对mongo多键复合查询执行和(带或不带mongoid),mongodb,mongoid,mongodb-query,Mongodb,Mongoid,Mongodb Query,我有以下格式的数据结构: { topAttribute: { subAttribute: [ { eventType: "SPECIAL", date: "20121231" } { eventType: "NOTSPECIAL", date: "20131012" } { eventType: "NOTSPECIAL", date: "20131122" } ...
{
topAttribute: {
subAttribute:
[
{ eventType: "SPECIAL", date: "20121231" }
{ eventType: "NOTSPECIAL", date: "20131012" }
{ eventType: "NOTSPECIAL", date: "20131122" }
...
]
}
}
我正在尝试识别eventType为“SPECIAL”且日期为“20121231”的记录。我正在尝试通过以下多键式查询来完成此操作:
Mongoid:
Item.where('topAttribute.subAttribute.eventType' => 'SPECIAL').and('topAttribute.subAttribute.date' => '20121231').all
MongoDB:
db.items.find( { 'topAttribute.subAttribute.eventType': 'SPECIAL', 'topAttribute.subAttribute.date': '20121231'} )
但是,当我运行此查询时,它会查找eventType为“SPECIAL”的记录或日期为“20121231”的记录。这不是我想要的结果
如何重新构造此查询(或使用另一种搜索/聚合策略)以仅显示eventType为“SPECIAL”的记录和日期为“20121231”的记录,并排除所有其他记录?如果要查找包含满足所有字段的数组元素的文档,需要使用运算符
db.items.find(
{ 'topAttribute.subAttribute' : {
$elemMatch: {
'eventType': 'SPECIAL',
'date': '20121231'
}
}
);