我所有的记录都有一个名为“图片”的字段。这个字段是一个字符串数组。

我现在想要最新的10条记录,其中这个数组不是空的。

我搜索了一下,但奇怪的是,我并没有在这方面找到太多。 我已经阅读了$where选项,但我想知道本机函数有多慢,如果有更好的解决方案。

即便如此,这也行不通:

ME.find({$where: 'this.pictures.length > 0'}).sort('-created').limit(10).execFind()

返回什么。离开这。没有长度位的图片也可以,但当然,它也会返回空记录。


当前回答

这可能对你也有用:

ME.find({'pictures.0': {$exists: true}});

其他回答

ME.find({pictures: {$exists: true}}) 

就这么简单,这招对我很管用。

你也可以使用帮手方法Exists代替Mongo操作符$ Exists

ME.find()
    .exists('pictures')
    .where('pictures').ne([])
    .sort('-created')
    .limit(10)
    .exec(function(err, results){
        ...
    });

经过更多的寻找,特别是在mongodb文档中,和令人费解的片段在一起,这是答案:

ME.find({pictures: {$exists: true, $not: {$size: 0}}})

您可以使用以下任何一种方法来实现此目的。 对于不包含所请求键的对象,两者都不会返回结果:

db.video.find({pictures: {$exists: true, $gt: {$size: 0}}})
db.video.find({comments: {$exists: true, $not: {$size: 0}}})

这也是可行的:

db.getCollection('collectionName').find({'arrayName': {$elemMatch:{}}})