651

私のすべてのレコードには、「写真」というフィールドがあります。このフィールドは文字列の配列です。

この配列が空ではない最新の10レコードが必要です。

私はグーグルで検索しましたが、不思議なことに、これについてはあまり見つかりませんでした。$ whereオプションを読みましたが、それがネイティブ関数に対してどれほど遅いか、そしてより良い解決策があるかどうか疑問に思いました。

そしてそれでも、それは機能しません:

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

何も返しません。長さビットなしで残すthis.picturesことは機能しますが、もちろん、空のレコードも返します。

4

13 に答える 13

1124

キーがないドキュメントもある場合は、次を使用できます。

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

$size関与している場合、MongoDBはインデックスを使用しないため、より良い解決策は次のとおりです。

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

プロパティに無効な値(またはその他)が含まれている可能性がある場合は、この回答で提案されているように、を使用null booleanして追加のチェックを追加します。$types

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、予期しない結果が生じる可能性があります(詳細な説明はこの回答にあります)。

ME.find({ pictures: { $gt: [] } })
于 2014-08-05T15:24:27.547 に答える
198

特にmongodbのドキュメントをもう少し調べて、パズルを解いた後、これが答えでした。

ME.find({pictures: {$exists: true, $not: {$size: 0}}})
于 2013-02-09T16:02:48.853 に答える
127

これもあなたのために働くかもしれません:

ME.find({'pictures.0': {$exists: true}});
于 2013-07-16T02:58:52.243 に答える
38

クエリを実行するときは、精度とパフォーマンスの2つに注意します。そのことを念頭に置いて、MongoDBv3.0.14でいくつかの異なるアプローチをテストしました。

TL; DRdb.doc.find({ nums: { $gt: -Infinity }})は最速で最も信頼性があります(少なくとも私がテストしたMongoDBバージョンでは)。

編集:これはMongoDB v3.6では機能しなくなりました!考えられる解決策については、この投稿の下のコメントを参照してください。

設定

リストフィールド付きの1kドキュメント、空のリスト付きの1kドキュメント、空でないリスト付きの5ドキュメントを挿入しました。

for (var i = 0; i < 1000; i++) { db.doc.insert({}); }
for (var i = 0; i < 1000; i++) { db.doc.insert({ nums: [] }); }
for (var i = 0; i < 5; i++) { db.doc.insert({ nums: [1, 2, 3] }); }
db.doc.createIndex({ nums: 1 });

これは、以下のテストのようにパフォーマンスを真剣に受け止めるには十分なスケールではないことを認識していますが、さまざまなクエリの正確性と選択したクエリプランの動作を示すには十分です。

テスト

db.doc.find({'nums': {'$exists': true}})間違った結果を返します(私たちが達成しようとしていることに対して)。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': {'$exists': true}}).count()
1005

-

db.doc.find({'nums.0': {'$exists': true}})正しい結果を返しますが、完全なコレクションスキャンを使用すると速度も遅くなります(COLLSCAN説明の段階に注意してください)。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': {'$exists': true}}).explain()
{
  "queryPlanner": {
    "plannerVersion": 1,
    "namespace": "test.doc",
    "indexFilterSet": false,
    "parsedQuery": {
      "nums.0": {
        "$exists": true
      }
    },
    "winningPlan": {
      "stage": "COLLSCAN",
      "filter": {
        "nums.0": {
          "$exists": true
        }
      },
      "direction": "forward"
    },
    "rejectedPlans": [ ]
  },
  "serverInfo": {
    "host": "MacBook-Pro",
    "port": 27017,
    "version": "3.0.14",
    "gitVersion": "08352afcca24bfc145240a0fac9d28b978ab77f3"
  },
  "ok": 1
}

-

db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}})間違った結果を返します。これは、無効なインデックススキャンがドキュメントを進めないためです。おそらく正確ですが、インデックスがないと遅くなります。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $gt: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 0,
  "executionTimeMillisEstimate": 0,
  "works": 2,
  "advanced": 0,
  "needTime": 0,
  "needFetch": 0,
  "saveState": 0,
  "restoreState": 0,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "$and": [
        {
          "nums": {
            "$gt": {
              "$size": 0
            }
          }
        },
        {
          "nums": {
            "$exists": true
          }
        }
      ]
    },
    "nReturned": 0,
    "executionTimeMillisEstimate": 0,
    "works": 1,
    "advanced": 0,
    "needTime": 0,
    "needFetch": 0,
    "saveState": 0,
    "restoreState": 0,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 0,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 0,
      "executionTimeMillisEstimate": 0,
      "works": 1,
      "advanced": 0,
      "needTime": 0,
      "needFetch": 0,
      "saveState": 0,
      "restoreState": 0,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "({ $size: 0.0 }, [])"
        ]
      },
      "keysExamined": 0,
      "dupsTested": 0,
      "dupsDropped": 0,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

-

db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}})正しい結果を返しますが、パフォーマンスが悪いです。技術的にはインデックススキャンを実行しますが、それでもすべてのドキュメントを進めてから、それらをフィルタリングする必要があります)。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $not: { '$size': 0 }}}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 2016,
  "advanced": 5,
  "needTime": 2010,
  "needFetch": 0,
  "saveState": 15,
  "restoreState": 15,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "$and": [
        {
          "nums": {
            "$exists": true
          }
        },
        {
          "$not": {
            "nums": {
              "$size": 0
            }
          }
        }
      ]
    },
    "nReturned": 5,
    "executionTimeMillisEstimate": 0,
    "works": 2016,
    "advanced": 5,
    "needTime": 2010,
    "needFetch": 0,
    "saveState": 15,
    "restoreState": 15,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 2005,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 2005,
      "executionTimeMillisEstimate": 0,
      "works": 2015,
      "advanced": 2005,
      "needTime": 10,
      "needFetch": 0,
      "saveState": 15,
      "restoreState": 15,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "[MinKey, MaxKey]"
        ]
      },
      "keysExamined": 2015,
      "dupsTested": 2015,
      "dupsDropped": 10,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

-

db.doc.find({'nums': { $exists: true, $ne: [] }})正しい結果を返し、わずかに高速ですが、パフォーマンスはまだ理想的ではありません。IXSCANを使用して、既存のリストフィールドでドキュメントを進めるだけですが、空のリストを1つずつ除外する必要があります。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $exists: true, $ne: [] }}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 1018,
  "advanced": 5,
  "needTime": 1011,
  "needFetch": 0,
  "saveState": 15,
  "restoreState": 15,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "$and": [
        {
          "$not": {
            "nums": {
              "$eq": [ ]
            }
          }
        },
        {
          "nums": {
            "$exists": true
          }
        }
      ]
    },
    "nReturned": 5,
    "executionTimeMillisEstimate": 0,
    "works": 1017,
    "advanced": 5,
    "needTime": 1011,
    "needFetch": 0,
    "saveState": 15,
    "restoreState": 15,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 1005,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 1005,
      "executionTimeMillisEstimate": 0,
      "works": 1016,
      "advanced": 1005,
      "needTime": 11,
      "needFetch": 0,
      "saveState": 15,
      "restoreState": 15,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "[MinKey, undefined)",
          "(undefined, [])",
          "([], MaxKey]"
        ]
      },
      "keysExamined": 1016,
      "dupsTested": 1015,
      "dupsDropped": 10,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

-

db.doc.find({'nums': { $gt: [] }})使用するインデックスに依存するため、予期しない結果が生じる可能性があるため、危険です。これは、ドキュメントを進めない無効なインデックススキャンが原因です。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ nums: 1 }).count()
0
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).hint({ _id: 1 }).count()
5

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: [] }}).explain('executionStats').executionStats.executionStages
{
  "stage": "KEEP_MUTATIONS",
  "nReturned": 0,
  "executionTimeMillisEstimate": 0,
  "works": 1,
  "advanced": 0,
  "needTime": 0,
  "needFetch": 0,
  "saveState": 0,
  "restoreState": 0,
  "isEOF": 1,
  "invalidates": 0,
  "inputStage": {
    "stage": "FETCH",
    "filter": {
      "nums": {
        "$gt": [ ]
      }
    },
    "nReturned": 0,
    "executionTimeMillisEstimate": 0,
    "works": 1,
    "advanced": 0,
    "needTime": 0,
    "needFetch": 0,
    "saveState": 0,
    "restoreState": 0,
    "isEOF": 1,
    "invalidates": 0,
    "docsExamined": 0,
    "alreadyHasObj": 0,
    "inputStage": {
      "stage": "IXSCAN",
      "nReturned": 0,
      "executionTimeMillisEstimate": 0,
      "works": 1,
      "advanced": 0,
      "needTime": 0,
      "needFetch": 0,
      "saveState": 0,
      "restoreState": 0,
      "isEOF": 1,
      "invalidates": 0,
      "keyPattern": {
        "nums": 1
      },
      "indexName": "nums_1",
      "isMultiKey": true,
      "direction": "forward",
      "indexBounds": {
        "nums": [
          "([], BinData(0, ))"
        ]
      },
      "keysExamined": 0,
      "dupsTested": 0,
      "dupsDropped": 0,
      "seenInvalidated": 0,
      "matchTested": 0
    }
  }
}

-

db.doc.find({'nums.0’: { $gt: -Infinity }})正しい結果を返しますが、パフォーマンスが低下します(完全なコレクションスキャンを使用します)。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).count()
5
MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums.0': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
  "stage": "COLLSCAN",
  "filter": {
    "nums.0": {
      "$gt": -Infinity
    }
  },
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 2007,
  "advanced": 5,
  "needTime": 2001,
  "needFetch": 0,
  "saveState": 15,
  "restoreState": 15,
  "isEOF": 1,
  "invalidates": 0,
  "direction": "forward",
  "docsExamined": 2005
}

-

db.doc.find({'nums': { $gt: -Infinity }})驚くべきことに、これは非常にうまく機能します!それは正しい結果をもたらし、それは高速で、インデックススキャンフェーズから5つのドキュメントを進めます。

MacBook-Pro(mongod-3.0.14) test> db.doc.find({'nums': { $gt: -Infinity }}).explain('executionStats').executionStats.executionStages
{
  "stage": "FETCH",
  "nReturned": 5,
  "executionTimeMillisEstimate": 0,
  "works": 16,
  "advanced": 5,
  "needTime": 10,
  "needFetch": 0,
  "saveState": 0,
  "restoreState": 0,
  "isEOF": 1,
  "invalidates": 0,
  "docsExamined": 5,
  "alreadyHasObj": 0,
  "inputStage": {
    "stage": "IXSCAN",
    "nReturned": 5,
    "executionTimeMillisEstimate": 0,
    "works": 15,
    "advanced": 5,
    "needTime": 10,
    "needFetch": 0,
    "saveState": 0,
    "restoreState": 0,
    "isEOF": 1,
    "invalidates": 0,
    "keyPattern": {
      "nums": 1
    },
    "indexName": "nums_1",
    "isMultiKey": true,
    "direction": "forward",
    "indexBounds": {
      "nums": [
        "(-inf.0, inf.0]"
      ]
    },
    "keysExamined": 15,
    "dupsTested": 15,
    "dupsDropped": 10,
    "seenInvalidated": 0,
    "matchTested": 0
  }
}
于 2017-03-04T20:49:39.793 に答える
32

2.6リリース以降、これを行う別の方法は、フィールドを空の配列と比較することです。

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

シェルでテストします。

> 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 ] }

picturesしたがって、少なくとも1つの配列要素があるドキュメントが適切に含まれ、pictures配列ではなく空の配列であるか、欠落しているドキュメントは除外されます。

于 2015-02-06T15:10:19.163 に答える
13

'pictures'が配列であり、空ではないすべてのドキュメントのみを取得します

ME.find({pictures: {$type: 'array', $ne: []}})

3.2より前のバージョンのMongoDbを使用している場合は、$type: 4の代わりにを使用して$type: 'array'ください。このソリューションは$sizeも使用しないため、インデックスに問題はありません(「クエリはクエリの$ size部分にインデックスを使用できません」)。

これらを含む他の解決策(受け入れられた答え):

ME.find({pictures:{$ examples:true、$ not:{$ size:0}}}); ME.find({写真:{$ examples:true、$ ne:[]}})

たとえば、「pictures」が、、 0などであっても、ドキュメントを返すため、間違っています。nullundefined

于 2018-09-23T11:51:53.460 に答える
6

これを実現するには、次のいずれかを使用できます。
どちらも、要求されたキーが含まれていないオブジェクトの結果を返さないように処理します。

db.video.find({pictures: {$exists: true, $gt: {$size: 0}}})
db.video.find({comments: {$exists: true, $not: {$size: 0}}})
于 2015-06-15T08:27:04.020 に答える
4
db.find({ pictures: { $elemMatch: { $exists: true } } })

$elemMatch指定されたクエリに一致する要素が少なくとも1つある配列フィールドを含むドキュメントに一致します。

したがって、すべての配列を少なくとも1つの要素と照合します。

于 2020-12-03T17:51:47.467 に答える
3

$elemMatch演算子を使用してください:ドキュメントによると

$ elemMatch演算子は、指定されたすべてのクエリ条件に一致する要素が少なくとも1つある配列フィールドを含むドキュメントと一致します。

$elemMatches値が配列であり、空でないことを確認してください。したがって、クエリは次のようになります

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

PSこのコードの変形は、MongoDB大学のM121コースにあります。

于 2019-05-19T20:43:46.647 に答える
0

ヘルパーメソッドExistsovertheMongo演算子$existsを使用することもできます

ME.find()
    .exists('pictures')
    .where('pictures').ne([])
    .sort('-created')
    .limit(10)
    .exec(function(err, results){
        ...
    });
于 2016-02-10T19:28:01.620 に答える
0
{ $where: "this.pictures.length > 1" }

$ whereを使用して、配列フィールドのサイズを返すthis.field_name.lengthを渡し、数値と比較して確認します。配列の値が配列サイズよりも大きい場合は、少なくとも1でなければなりません。したがって、すべての配列フィールドの長さが1を超える場合は、その配列にデータがあることを意味します。

于 2018-02-28T06:16:51.703 に答える
0

これも機能します:

db.getCollection('collectionName').find({'arrayName': {$elemMatch:{}}})
于 2020-11-13T19:17:30.517 に答える
-9
ME.find({pictures: {$exists: true}}) 

そのように単純で、これは私にとってはうまくいきました。

于 2015-02-09T20:29:28.370 に答える