Manu Masson
Manu Masson

Reputation: 1737

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.

Upvotes: 4

Views: 12880

Answers (3)

Ahmad MOUSSA
Ahmad MOUSSA

Reputation: 2906

As mentioned by @alexmac, this works for me:

collection.find({}, '_id')

Upvotes: 0

colkito
colkito

Reputation: 31

You could use the distinct method in order to get an array of _id for your query.

Follow this question

Upvotes: 3

zero298
zero298

Reputation: 26878

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();

Upvotes: 4

Related Questions