我有一个Pymango收藏,形式如下:
{
"_id" : "R_123456789",
"supplier_ids" : [
{
"id" : "S_987654321",
"file_version" : ISODate("2016-03-15T00:00:00Z"),
"latest" : false
},
{
"id" : "S_101010101",
"file_version" : ISODate("2016-03-29T00:00:00Z"),
"latest" : true
}
]
}
当我获得新的供应商数据时,如果供应商ID发生了变化,我想通过将前一个“latest”上的latest设置为False并将$push设置为新记录来捕获它。你知道吗
$set无法工作,因为我正在尝试使用它(在'else'后面注释代码):
import pymongo
from dateutil.parser import parse
new_id = 'S_323232323'
new_date = parse('20160331')
with pymongo.MongoClient() as client:
db = client.transactions
collection_ids = db.ids
try:
collection_ids.insert_one({"_id": "R_123456789",
"supplier_ids": ({"id": "S_987654321",
"file_version": parse('20160315'),
"latest": False},
{"id": "S_101010101",
"file_version": parse('20160329'),
"latest": True})})
except pymongo.errors.DuplicateKeyError:
print('record already exists')
record = collection_ids.find_one({'_id':'R_123456789'})
for supplier_id in record['supplier_ids']:
print(supplier_id)
if supplier_id['latest']:
print(supplier_id['id'], 'is the latest')
if supplier_id['id'] == new_id:
print(new_id, ' is already the latest version')
else:
# print('setting', supplier_id['id'], 'latest flag to False')
# <<< THIS FAILS >>>
# collection_ids.update_one({'_id':record['_id']},
# {'$set':{'supplier_ids.latest':False}})
print('appending', new_id)
data_to_append = {"id" : new_id,
"file_version": new_date,
"latest": True}
collection_ids.update_one({'_id':record['_id']},
{'$push':{'supplier_ids':data_to_append}})
非常感谢您的帮助。你知道吗
整个过程似乎异常冗长-我应该使用更精简的方法吗?你知道吗
谢谢!你知道吗
可以尝试使用位置运算符。你知道吗
如果该查询在文档中为true并且与其他条件匹配,则该查询将更新
supplier_ids.latest = false
。你知道吗关键是你必须包括字段数组作为条件的一部分。你知道吗
有关详细信息,请参见Update
相关问题 更多 >
编程相关推荐