Search code examples
mongodbmongodb-queryint64

how to query mongodb long fields?


Suppose I am creating a mongodb collection from pymongo in this way:

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
#create db
mydb = myclient["query_int64"]
#mydb.command('create', 'timeseriesCollection', {"timeseries":{ 'timeField': 'timestamps', 'metaField': 'metadata'}})
validator = {
    "$jsonSchema": {
        "bsonType": "object",
        "required": ["timestamp", "value"],
        "properties": {
            "timestamp": {
                "bsonType": "long",
            },
            "value": {
                "bsonType": "double"
            },
        }
    }
}
res = mydb.command("collMod", "timeseriesCollection", validator=validator)
print(res)
mydb.timeseriesCollection.insert_one({"timestamp": 1688138933864487000, "value": 12.2})
mydb.timeseriesCollection.insert_one({"timestamp": 1688138933947443000, "value": 14.2})

From mongo compass I am trying to query on the timestamp field. I've tried both:

{"timestamp": {"$eq": 1688138933864487000}}

and

{"timestamp": 1688138933864487000}

but it's returning empty.

How to query int64 fields for equality, less than, great than and a combination of the last 2 in mongodb ?


Solution

  • So I found a solution: in mongo shell or in client GUI such as Mongodb Compass, the query returning results is:

    {"timestamp": NumberLong("1688138933947443000")}
    

    Being the type an int64.

    In pymongo it is more straightforward:

    mydb.timeseriesCollection.find_one({"timestamp": 1688138933864487000})