【问题标题】:Performing AND on mongo multikey compound query (with or without mongoid)在 mongo 多键复合查询上执行 AND(有或没有 mongoid)
【发布时间】:2014-08-03 14:47:55
【问题描述】:

我有如下格式的数据结构:

{
  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'} ) 

但是,当我运行此查询时,它会发现 either 记录的 eventType 为“SPECIAL”OR 记录的日期为“20121231”。这不是我想要的结果。

我如何重组这个查询——或者使用其他搜索/聚合策略——只显示事件类型为“SPECIAL”的记录AND日期为“20121231”的记录,并排除所有其他的?

【问题讨论】:

    标签: mongodb mongoid mongodb-query


    【解决方案1】:

    当您想查找包含满足所有字段的数组元素的文档时,您需要使用$elemMatch 运算符。

    db.items.find( 
        { 'topAttribute.subAttribute' : {
            $elemMatch: {
                 'eventType': 'SPECIAL',
                 'date': '20121231'
            }
        } 
    );
    

    【讨论】:

      猜你喜欢
      • 2012-09-01
      • 2019-05-06
      • 1970-01-01
      • 2014-10-22
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多