Level / community

Discussion, support and common information for projects in the community.
MIT License
42 stars 15 forks source link

Counting entries in a level database #96

Closed prepconcede closed 2 years ago

prepconcede commented 3 years ago

Sorry if this is a stupid question, but i really need to count database entries. How can I achieve that? Thanks in advance

juliangruber commented 3 years ago

something like this should work:

let entries = 0
db.createKeyStream().on('data', () => entries++).on('end', () => console.log({ entries }))

or check out https://github.com/voltraco/level-count#readme

juliangruber commented 3 years ago

Basically you create a stream of all the keys, and count how many entries it emits. There are multiple ways to do the stream objects counting bit, eg:

let entries = 0
for await (const key of db.createKeyStream()) {
  entries++
}
console.log({ entries })
vweevers commented 3 years ago

Let's not close so fast; it's a good question because level doesn't offer any solution out of the box and that's because the best solution depends on data & app characteristics. E.g.:

juliangruber commented 3 years ago

Thank you for reopening, you're right that I addressed this naively. I guess this was the solution for my past use cases.