本文翻譯自: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
沒有長度位的確可以,但是當然它也返回空記錄。
#1樓
參考:https://stackoom.com/question/103TI/查找數組字段不爲空的MongoDB記錄
#2樓
經過一番摸索之後,尤其是在mongodb文檔中,又使人困惑不解,這就是答案:
ME.find({pictures: {$exists: true, $not: {$size: 0}}})
#3樓
這也可能對您有用:
ME.find({'pictures.0': {$exists: true}});
#4樓
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: [] } })
#5樓
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。
#6樓
ME.find({pictures: {$exists: true}})
就這麼簡單,這對我有用。