我的时间序列对象:
{
"timestamp": datetime object,
"field1": "somestring",
"metadata": {
"type": 1,
"location": "Hong Kong"
}
}
我为我的
metadata
字段创建一个索引:
collection = db.create_collection(
"market-catalog-time-series",
timeseries={
"timeField": "timestamp",
"metaField": "metadata",
"granularity": "seconds",
},
)
db.collection.createIndex('metadata')
之后我想查询数据:
res = db.collection.find({"metadata": {"type": 1, "location": "Hong Kong"}})
print(list(res))
但是,我得到了
[]
,请问为什么?
TL;DR:删除
db.
前缀,仅执行 res = collection.find(...)
或 db.get_collection("market-catalog-time-series").find(...)
。
说明:您正在创建一个名为
market-catalog-time-series
的集合,并将其分配给 变量 collection
。已经有一个来自 db.create_collection(...)
的父数据库。
但是在
res = db.collection.find(...)
中,它表示父数据库 collection
名为 db
的 集合。该集合可能不存在并且与您想要的不同。
db.collection.createIndex('metadata')
同样的问题。实际方法是create_index()
而不是createIndex()
。它应该只是 collection.create_index('metadata')
或 db.get_collection("market-catalog-time-series").create_index('metadata')
所以完整的代码是:
collection = db.create_collection(
"market-catalog-time-series",
timeseries={
"timeField": "timestamp",
"metaField": "metadata",
"granularity": "seconds",
},
)
collection.create_index('metadata')
res = collection.find({"metadata": {"type": 1, "location": "Hong Kong"}})
print(list(res))