本文翻译自:Find MongoDB records where array field is not empty
All of my records have a field called "pictures". 我所有的记录都有一个名为“图片”的字段。 This field is an array of strings. 该字段是字符串数组。
I now want the newest 10 records where this array IS NOT empty. 我现在想要该数组不为空的最新10条记录。
I've googled around, but strangely enough I haven't found much on this. 我在Google上四处搜寻,但奇怪的是,我在这方面没有发现太多。 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. 我已经读过$ where选项,但是我想知道这对本机函数有多慢,以及是否有更好的解决方案。
And even then, that does not work: 即使这样,它也不起作用:
ME.find({$where: 'this.pictures.length > 0'}).sort('-created').limit(10).execFind()
Returns nothing. 不返回任何内容。 Leaving this.pictures
without the length bit does work, but then it also returns empty records, of course. 留下this.pictures
没有长度位的确可以,但是当然它也返回空记录。
参考:https://stackoom.com/question/103TI/查找数组字段不为空的MongoDB记录
经过一番摸索之后,尤其是在mongodb文档中,又使人困惑不解,这就是答案:
ME.find({pictures: {$exists: true, $not: {$size: 0}}})
这也可能对您有用:
ME.find({'pictures.0': {$exists: true}});
If you also have documents that don't have the key, you can use: 如果您还有没有密钥的文档,则可以使用:
ME.find({ pictures: { $exists: true, $not: {$size: 0} } })
MongoDB don't use indexes if $size is involved, so here is a better solution: 如果涉及$ size,MongoDB不会使用索引,因此这是一个更好的解决方案:
ME.find({ pictures: { $exists: true, $ne: [] } })
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 ): 从MongoDB 2.6版本开始,您可以与运算符$gt
进行比较,但可能会导致意外的结果(您可以在此答案中找到详细的说明):
ME.find({ pictures: { $gt: [] } })
Starting with the 2.6 release, another way to do this is to compare the field to an empty array: 从2.6版本开始,另一种方法是将字段与一个空数组进行比较:
ME.find({pictures: {$gt: []}})
Testing it out in the shell: 在外壳中进行测试:
> db.ME.insert([
{pictures: [1,2,3]},
{pictures: []},
{pictures: ['']},
{pictures: [0]},
{pictures: 1},
{foobar: 1}
])
> db.ME.find({pictures: {$gt: []}})
{ "_id": ObjectId("54d4d9ff96340090b6c1c4a7"), "pictures": [ 1, 2, 3 ] }
{ "_id": ObjectId("54d4d9ff96340090b6c1c4a9"), "pictures": [ "" ] }
{ "_id": ObjectId("54d4d9ff96340090b6c1c4aa"), "pictures": [ 0 ] }
So it properly includes the docs where pictures
has at least one array element, and excludes the docs where pictures
is either an empty array, not an array, or missing. 因此,它适当地包括pictures
至少具有一个数组元素的docs,并排除pictures
为空数组,不是数组或缺失的docs。
ME.find({pictures: {$exists: true}})
就这么简单,这对我有用。