Python MongoDB没有';不尊重max的封顶收藏
以下是我创建该系列的方式:Python MongoDB没有';不尊重max的封顶收藏,python,python-3.x,mongodb,pymongo,Python,Python 3.x,Mongodb,Pymongo,以下是我创建该系列的方式: def connect(self): self.client = MongoClient(self.ip, self.port) try: capped = self.max_size != None print("capped", capped) print("max", self.max_size) self.coll = self.client[self.db_name].creat
def connect(self):
self.client = MongoClient(self.ip, self.port)
try:
capped = self.max_size != None
print("capped", capped)
print("max", self.max_size)
self.coll = self.client[self.db_name].create_collection(self.coll_name, capped=capped, max=self.max_size)
except:
self.coll = self.client[self.db_name][self.coll_name]
self.coll.create_index([('expireAt', 1)], expireAfterSeconds=0)
conn.test.create_collection('test', capped=True, size=10000, max=5)
for i in range(10):
conn.test.test.insert_one({'_id': i})
我将self.max_size
设置为10
然后,我试了一下:
for i in range(20):
cache.put(i, {'id': i})
我希望在收藏中能看到10个10
文档,但实际上所有20个文档都在收藏中
为什么?
更新:我在mongo shell中运行了以下命令:
db.getCollection('test').isCapped()
我得到了
假的
您需要size
和max
参数来创建封顶集合:
def connect(self):
self.client = MongoClient(self.ip, self.port)
try:
capped = self.max_size != None
print("capped", capped)
print("max", self.max_size)
self.coll = self.client[self.db_name].create_collection(self.coll_name, capped=capped, max=self.max_size)
except:
self.coll = self.client[self.db_name][self.coll_name]
self.coll.create_index([('expireAt', 1)], expireAfterSeconds=0)
conn.test.create_collection('test', capped=True, size=10000, max=5)
for i in range(10):
conn.test.test.insert_one({'_id': i})
在mongo
shell中:
> db.test.find()
{ "_id" : 5 }
{ "_id" : 6 }
{ "_id" : 7 }
{ "_id" : 8 }
{ "_id" : 9 }
> db.test.isCapped()
true
如果尝试在不使用size
参数的情况下创建它,它将输出一个错误:
pymongo.errors.OperationFailure: the 'size' field is required when 'capped' is true
但是,您的代码有一个try…除了
参数。因此它遇到了这个错误,然后继续执行except
子句,这样您就看不到产生了错误并且没有创建封顶集合。您需要size
和max
参数来创建封顶集合:
def connect(self):
self.client = MongoClient(self.ip, self.port)
try:
capped = self.max_size != None
print("capped", capped)
print("max", self.max_size)
self.coll = self.client[self.db_name].create_collection(self.coll_name, capped=capped, max=self.max_size)
except:
self.coll = self.client[self.db_name][self.coll_name]
self.coll.create_index([('expireAt', 1)], expireAfterSeconds=0)
conn.test.create_collection('test', capped=True, size=10000, max=5)
for i in range(10):
conn.test.test.insert_one({'_id': i})
在mongo
shell中:
> db.test.find()
{ "_id" : 5 }
{ "_id" : 6 }
{ "_id" : 7 }
{ "_id" : 8 }
{ "_id" : 9 }
> db.test.isCapped()
true
如果尝试在不使用size
参数的情况下创建它,它将输出一个错误:
pymongo.errors.OperationFailure: the 'size' field is required when 'capped' is true
但是,您的代码有一个try…除了
参数。所以它遇到了这个错误,然后转到except
子句,这样您就看不到产生了错误,也没有创建capped集合