gpt4 book ai didi

mongodb - 查找数组字段不为空的 MongoDB 记录

转载 作者:IT老高 更新时间:2023-10-28 11:10:46 24 4
gpt4 key购买 nike

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

我现在想要这个数组不为空的最新 10 条记录。

我已经用谷歌搜索了,但奇怪的是我没有找到太多关于这个的东西。我已经阅读了 $where 选项,但我想知道这对原生函数有多慢,以及是否有更好的解决方案。

即使那样,这也行不通:

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

什么都不返回。离开 this.pictures 没有长度位确实有效,但当然它也会返回空记录。

最佳答案

如果您还有没有 key 的文档,您可以使用:

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版本开始,你可以用$gt这个操作符进行比较,但这可能会导致意想不到的结果(你可以找到详细的解释in this answer):

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

关于mongodb - 查找数组字段不为空的 MongoDB 记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14789684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com