2017-08-03 138 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鍵$匹配運算符的過濾器的文件不會通過$執行放鬆階段集中返回的結果存在到文檔中。