2016-07-21 40 views
3

存在我有我的數據庫集合如下因素對象結構:

{ 
    "name" : "test", 
    "code" : "test", 
    "attributes" : [ 
     { 
      "name" : "test1", 
      "code" : "code1" 
     }, 
     { 
      "name" : "test2", 
      "code" : "code2", 
      "value" : true 
     }, 
     { 
      "name" : "test3", 
      "code" : "code3", 
      "value" : "" 
     }, 
     { 
      "name" : "test4", 
      "code" : "code4" 
      "value" : [ 
       { 
        "code" : "code4.1", 
        "name" : "test4.1" 
       }, 
       { 
        "name" : "test4.2" 
       } 
      ] 
     } 
    ] 
} 

因此,「價值」屬性可以爲空字符串,布爾值,數組甚至根本定義。

如何使查詢列出具有非空屬性數組的對象並且在數組中至少有一個對象內沒有定義「attributes.value」屬性?

p.s.我試過以下查詢:

db.collection.find({"attributes": {$exists: true, $ne: []}, "attributes.value": {$exists: false}}) 

但查詢結果爲空。

回答

5

的$ elemMatch操作者匹配包含的陣列字段 與所有指定的查詢 條件匹配的至少一種元素的文檔。

我這個查詢工作:

db.getCollection('testeur').find({ "attributes": { 
     $exists: true, 
     $ne: [], 
     $elemMatch: { "value": {$exists: false } } 
    } 
}) 
+0

感謝,這正是我一直在尋找。 –