我所有的记录都有一个名为"图片"的字段.此字段是字符串array.
我现在想要最新的10条记录,其中数组不是空的.
我在谷歌上搜索过,但奇怪的是,我没有在这方面找到多少.
即便如此,这也行不通:
ME.find({$where: 'this.pictures.length > 0'}).sort('-created').limit(10).execFind()
不返回任何内容.保留this.pictures
而不保留长度位确实有效,但它当然也会返回空记录.
我所有的记录都有一个名为"图片"的字段.此字段是字符串array.
我现在想要最新的10条记录,其中数组不是空的.
我在谷歌上搜索过,但奇怪的是,我没有在这方面找到多少.
即便如此,这也行不通:
ME.find({$where: 'this.pictures.length > 0'}).sort('-created').limit(10).execFind()
不返回任何内容.保留this.pictures
而不保留长度位确实有效,但它当然也会返回空记录.
如果您还有没有密钥的文档,可以使用:
ME.find({ pictures: { $exists: true, $not: {$size: 0} } })
如果涉及$size
,MongoDB不使用索引,所以这里有一个更好的解决方案:
ME.find({ pictures: { $exists: true, $ne: [] } })
如果您的属性可能有无效值(如null
boolean
或其他),则您可以添加一个额外的复选框using $types
,如建议的in this answer:
使用mongo>;=3.2:
ME.find({ pictures: { $exists: true, $type: 'array', $ne: [] } })
与mongo<;3.2:
ME.find({ pictures: { $exists: true, $type: 4, $ne: [] } })
自MongoDB 2.6发布以来,您可以与operator $gt
进行比较,但这可能会导致意外的结果(您可以找到详细的解释in this answer):
ME.find({ pictures: { $gt: [] } })