2017-07-19 88 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