查找数组字段不为空的MongoDB记录 [英] Find MongoDB records where array field is not empty

查看:68
本文介绍了查找数组字段不为空的MongoDB记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的所有记录都有一个名为图片"的字段.此字段是字符串数组.

All of my records have a field called "pictures". This field is an array of strings.

我现在想要该数组不为空的最新10条记录.

I now want the newest 10 records where this array IS NOT empty.

我已经在Google周围搜索,但奇怪的是,我在这方面没有发现太多. 我已经读过$ where选项,但是我想知道这对本机函数有多慢,以及是否有更好的解决方案.

I've googled around, but strangely enough I haven't found much on this. I've read into the $where option, but I was wondering how slow that is to native functions, and if there is a better solution.

即使那样,它也不起作用:

And even then, that does not work:

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

不返回任何内容.不用this.pictures保留长度位确实可以,但是当然它也返回空记录.

Returns nothing. Leaving this.pictures without the length bit does work, but then it also returns empty records, of course.

推荐答案

如果您还有没有密钥的文档,则可以使用:

If you also have documents that don't have the key, you can use:

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

如果涉及$ size,MongoDB不使用索引,因此这是一个更好的解决方案:

MongoDB don't use indexes if $size is involved, so here is a better solution:

ME.find({ pictures: { $exists: true, $ne: [] } })

自MongoDB 2.6版本以来,您可以与运算符$gt进行比较,但可能导致意外的结果(您可以找到详细的解释

Since MongoDB 2.6 release, you can compare with the operator $gt but could lead to unexpected results (you can find a detailled explanation in this answer):

ME.find({ pictures: { $gt: [] } })

这篇关于查找数组字段不为空的MongoDB记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆