2017-07-19 82 views
0

數組文件查詢完成我有一個folders集合內的下列文件:的MongoDB:在包含對象

folders: [ 
    { _id : 1, 
     docs : [ 
      { foo : 1, 
       bar : undefined}, 
      { foo : 3, 
       bar : 3} 
      ] 
    }, 
    { _id : 2, 
     docs : [ 
      { foo : 2, 
       bar : 2}, 
      { foo : 3, 
       bar : 3} 
      ] 
    }, 
    { _id : 3, 
     docs : [ 
      { foo : 2}, 
      { foo : 3, 
       bar : 3} 
      ] 
    }, 
    { _id : 4, 
     docs : [ 
      { foo : 1 } 
      ] 
    }, 
    { _id : 5, 
     docs : [ 
      { foo : 1, 
       bar : null } 
      ] 
    } 
] 

我需要能夠查詢沒有一個undefined價值的文件,null值,或不存在的值爲docs.bar。在上面的情況下,查詢應該只返回文檔_id: 2。我目前有一個解決方案,但我想知道是否有更好的方式來查詢文件。

我目前的解決方案:

db.folders.find({$nor: [{"docs.bar": { $exists: false }}]})

+0

原來我的解決方案返回了一個誤報。然而@glitch提供的[answer](https://stackoverflow.com/questions/45189590/mongodb-querying-for-completion-in-documents-containing-an-array-of-objects/45195904#45195904)卻是正確的。 –

回答

0

這...

db.folder.find({"docs.bar": {$exists: true}, "docs.bar": {$ne: null}}) 

...只會返回其中至少docs陣列中的子文件之一有那些條目一個填充的bar屬性。注意:在這個查詢中,兩個謂詞是「與」的,我認爲這符合您的要求,它肯定會返回您提供的集合中的文檔_id: 2