Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

only return document _id on mongoose .find()

I update 100's of documents every second by pushing new data to an array in its document. To get the document of which I am going to add data to, I use the mongoose .find().limit(1) function, and return the whole document. It works fine.

To help with some memory and cpu issues I have, I was wondering how I could get find() to only return the id of the document so I can use that to $push or $set new data.

Thanks.

like image 695
Manu Masson Avatar asked Oct 24 '25 07:10

Manu Masson


1 Answers

You want to use Projection to tell your query exactly what you want off of your objects.

_id is always included unless you tell it not to.

readings = await collection
.find({
    name: "Some name you want"
})
.project({
    _id: 1 // By default
})
.toArray();
like image 125
zero298 Avatar answered Oct 26 '25 21:10

zero298