

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# \$1changeStream
<a name="changeStream"></a>

Elastic 叢集不支援。

`$changeStream` 彙總階段會開啟變更串流游標，以監控集合的即時變更。當發生插入、更新、取代或刪除操作時，它會傳回變更事件文件。

**參數**
+ `fullDocument`：指定是否要傳回更新操作的完整文件。選項為 `default` 或 `updateLookup`。
+ `resumeAfter`：選用。繼續字符，從變更串流中的特定點繼續。
+ `startAtOperationTime`：選用。開始變更串流的時間戳記。
+ `allChangesForCluster`：選用。布林值。當 時`true`， 會監控叢集的所有變更 （適用於管理員資料庫）。當 `false`（預設） 時， 只會監看指定的集合。

## 範例 (MongoDB Shell)
<a name="changeStream-examples"></a>

下列範例示範如何使用 `$changeStream`階段來監控集合的變更。

**查詢範例**

```
// Open change stream first
const changeStream = db.inventory.aggregate([
  { $changeStream: { fullDocument: "updateLookup" } }
]);

// In another session, insert a document
db.inventory.insertOne({ _id: 1, item: "Widget", qty: 10 });

// Back in the first session, read the change event
if (changeStream.hasNext()) {
  print(tojson(changeStream.next()));
}
```

**輸出**

```
{
  _id: { _data: '...' },
  operationType: 'insert',
  clusterTime: Timestamp(1, 1234567890),
  fullDocument: { _id: 1, item: 'Widget', qty: 10 },
  ns: { db: 'test', coll: 'inventory' },
  documentKey: { _id: 1 }
}
```

## 程式碼範例
<a name="changeStream-code"></a>

若要檢視使用`$changeStream`彙總階段的程式碼範例，請選擇您要使用的語言標籤：

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('inventory');

  // Open change stream
  const changeStream = collection.watch([]);

  changeStream.on('change', (change) => {
    console.log('Change detected:', change);
  });

  // Simulate insert in another operation
  setTimeout(async () => {
    await collection.insertOne({ _id: 1, item: 'Widget', qty: 10 });
  }, 1000);

  // Keep connection open to receive changes
  // In production, handle cleanup appropriately
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient
import threading
import time

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['inventory']

    # Open change stream
    change_stream = collection.watch([])

    # Insert document in separate thread after delay
    def insert_doc():
        time.sleep(1)
        collection.insert_one({'_id': 1, 'item': 'Widget', 'qty': 10})

    threading.Thread(target=insert_doc).start()

    # Watch for changes
    for change in change_stream:
        print('Change detected:', change)
        break  # Exit after first change

    client.close()

example()
```

------