2017-08-03 130 views
1

假设我们AA场检索文件有类似以下数据的集合:它不包含布尔值

{ 
    "_id":"4313e7aa192d75b7c3cffc8af0312fdeb", 
    "name":"Foo", 
    "services":[ 
     { 
     "serviceID":"378e7aa192d75b7c3cffc8aq033fdeb", 
     "isActive":true 
     }, 
     { 
     "serviceID":"5403e7aa192d75b7c3cffc8af033fdex", 
     "isActive":false 
     }, 
     { 
     "serviceID":"e918e7aa192d75b7c3cffc8ax0233fdey", 
     "isActive":true 
     } 
    ] 
}, 
{ 
    "_id":"b1d8b857963e35521faef87d215ca3f7", 
    "name":"Foo", 
    "services":[ 
     { 
     "serviceID":"b98857963e35521faef87d215ca3f8", 
     "isActive":false 
     } 
    ] 
}, 
{ 
    "_id":"34efdb9e62c2131e050917b4524d6e6f", 
    "name":"Foo", 
    "services":[ 
     { 
     "serviceID":"39efba9e62c2131e050917b4524d6e6f", 
     "isActive":false 
     }, 
     { 
     "serviceID":"34ex1b9e62c2131e050917b4524d6e6x", 
     "isActive":false 
     } 
    ] 
} 

现在,我们怎样才能使一个查询检索哪些还没有任何活动服务的文档(我是指不包含"isActive":true)?有没有这样的查询运营商?

任何想法,将不胜感激......

回答

0

怎么样简单的东西,因为这:

collection.find({ "services.isActive": { $ne: true } }) 
0

如果结果文档你不介意的服务阵列中也看到的那些地方isActive = true,那么@无需编写就足够了。

如果你的头脑,试试这个:

db.collection.aggregate([ 
{ 
    $unwind: "$services" 
}, 
{ 
    $match: { 
     "services.isActive": false 
    } 
} 
]) 
0

根据描述在提问中所提请尝试执行以下汇总查询到MongoDB的外壳

db.collection.aggregate(

    // Pipeline 
    [ 
     // Stage 1 
     { 
      $unwind: "$services" 
     }, 

     // Stage 2 
     { 
      $match: { 
      $or:[ 
      {'services.isActive':{$exists:false}}, 
      {'services.isActive':false} 

      ] 
      } 
     }, 

    ] 



); 

上面提到的聚集查询执行多个汇总流水线的阶段

$ unwind运算符将数组分割为单独的文档,用于每个数组元素。

包括关键isActive值为假或任isActive键$匹配运算符的过滤器的文件不会通过$执行放松阶段集中返回的结果存在到文档中。