Limit option is not working for changestream.watch

Hi Team,

I am trying to add limit for changestream watch, however it is throwing below error.
kindly help me to fix this issue.

My code:

var cursor = rulesCollection.Watch(options).limit(2)

Error:
CS1016: IChangeStreamCursor<ChangeStreamDocument> does not contain a definition for limit and no accessible extension method. Limit accepting a first argument of type IChangeStreamCursor<ChangeStreamDocument> could be found (are you missing a using directive or an assembly reference?)

Thanks,
Lalitha.C

Hi @Lalitha_Chevuru and welcome to MongoDB community forums!!

Although I attempted to use the limit function while watching the change stream, it appears that the current implementation does not support limiting the display of updated fields.

To further explore this issue, I loaded a sample document in my local environment.

{
    _id: ObjectId("645cbb9f0119476b03b2ba0e"),
    DaysSinceLastSale: 81,
    IsResidential: true,
    Owner1NameFull: 'Henry Hunter',
    AddressCity: 'Newport News',
    AddressState: 'Hawaii',
    AddressZIP: 264142,
    position: [ -50.32564, 69.42805 ],
    year: '2020'
  }

and tried the following python code:

from pymongo import MongoClient
    import itertools
   
    client = MongoClient('mongodb://localhost:27017')
    db = client['test']
    collection = db['sample']
   
    pipeline = [  { '$match': { 'year': '2020' } },  { '$project': { '_id': 0 } }]
   
    change_stream = collection.watch()
   
    for change in itertools.islice(change_stream, 7):
       print(change)

with the update command as:

replset [direct: primary] test> db.sample.updateMany( { DaysSinceLastSale: { $gt: 40}}, { $set: { year: '2027'}})
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 12002,
  modifiedCount: 12002,
  upsertedCount: 0
}

The change stream retuned exactly 7 documents.

Therefore, as Limit() is not a built-in feature of change streams, you can implement it at the application code level to achieve the desired functionality.

Let us know if you have further questions.

Regards
Aasawari