Home > database >  Not able to query mongodb data within a range of time
Not able to query mongodb data within a range of time

Time:01-19

I have a mongodb collection like this:


[{
  "_id": {
    "$oid": "63b79f9e5c98b4aa46719920"
  },
  "time": {
    "$numberLong": "1672978334287"
  },
  "tvl": 0.005495200757897796,
  "wethToken1": true
},{
  "_id": {
    "$oid": "63b79fad5c98b4aa46719921"
  },
  "time": {
    "$numberLong": "1672978349046"
  },
  "tvl": 0.010990401515795592,
  "wethToken1": true
},{
  "_id": {
    "$oid": "63b7a0ee5c98b4aa46719922"
  },
  "time": {
    "$numberLong": "1672978670070"
  }]

I want to query the data but i want a to param (from is aways Date.now())

So i wrote this query:


const queryTVL = async (from) => {
    // const formatedFrom = NumberLong(from)
    // const formatedTo = NumberLong(to)
    try {
        const collection = await mongoClient.db("tangle-db").collection("tvl")
        const documents = await collection.find({
            "time": {
                "$gt": from
            }
        }).toArray()
        let docArr = []
            documents.map((data) => {
                    console.log(data, 'data')
                    docArr.push({
                        tvl: data.tvl,
                        time: data.time
                    })
            })
        console.log(docArr)
        return docArr
    } catch (error) {
        console.log(error, 'for getLastTVL')
    }
}

But docArr aways return empity, something is wrong with this block:


        const documents = await collection.find({
            "time": {
                "$gt": from
            }

Can someone give me a hint?

CodePudding user response:

I believe you could specify "time.$numberLong" in your find() to find the actual number.

CodePudding user response:

You need to specify NumberLong to the integer as used while inserting it:

db.collection.find({
  "time": {
    "$gt": NumberLong("1672978349046")
  }
})
  • Related