Home > OS >  Why does slice() not work on an Array output from MongoDB find()?
Why does slice() not work on an Array output from MongoDB find()?

Time:07-05

In mongosh, I execute these commands:

[{title: '111'}, {title: '222'}].forEach(doc => console.log(doc.title))
[{title: '111'}, {title: '222'}].slice(0,1)

db.todos.find().forEach(doc => console.log(doc.title))
db.todos.find().slice(0,1)

and get this output:

enter image description here

Why does .slice() not work on the array coming from the MongoDB command db.todos.find()?

CodePudding user response:

The find() method returns a FindCursor that manages the results of your query. You can iterate through the matching documents using one of the following cursor methods:

next() toArray() forEach()

Try:

db.todos.find().toArray().slice(0,1)

https://www.mongodb.com/docs/drivers/node/current/usage-examples/find/#find-multiple-documents

  • Related