2015-09-17 63 views
1

我需要只检索有format.prices阵列中的至少一个元素的记录和price是0到0.99之间和每一个元素:

所以这个工作得很好的price比较:

{ 'formats.prices': { $not: { $elemMatch: { price: { $gt: 0, $lte: 0.99 } } } } } 

但我怎么可以添加像$not: { $size: 0 }条件也排除了formats.prices没有在所有的元素吗?

回答

1

嗯,我这个结束,它工作正常,不知道是否有更好的办法:

{ 
    'formats.prices': { $not: { $elemMatch: { price: { $gt: 0, $lte: 0.99 } } } }, 
    'formats.prices.0.price': { $exists: true } 
} 
+1

这是更好喜欢它。假设你有一个关于“formats.prices.price”的索引(这可能是一个好主意,考虑到你想要进行范围查询,尽管现在是排除在外),那么这里的$ exists测试可以实际使用它, $ not:{$ size:0}'不能。尽管如此,对于积极的价格来说,除非你的真实意图是数组中没有价格落入该范围内,否则做一个积极匹配'{'formats.prices.price':{$ gt:0.99}}'会更好。 。这实际上是你如何提出问题的反驳。 –

+0

非常感谢@BlakesSeven很高兴这是最好的选择,对于应用程序的意图是我误解了这个问题,因为我需要没有价格落在该范围内(并且至少不是一个)。 (更新它) –