我在Python中使用MongoEngine來處理我的數據模型。追加到文檔內的列表中的子文檔中的列表?
我有一個數據模型基本上看起來像這樣在BSON表示:
{
'id': ...
'revisions': [
{
'id': ...
'revision': 1,
'derivatives': [
{
'id': ...
'name': 'Derivative 1'
}
]
}
]
}
我們會打電話給owner
最外面的文件,在owner.revisions
所有的子文檔將被稱爲revision
,並在revision.derivatives
所有的子文檔將被稱爲derivative
。
我期待$addToSet
到derivatives
設置在特定owner
內的特定revision
內。如果讓我用Python寫這個,它會是這樣的:
def add_to_set(owner_id, revision_id, new_derivative):
for owner in owner_collection:
if owner.id == owner_id:
# found the right owner
for revision in owner.revisions:
if revision.id == revision_id:
# we've found the right revision in the right owner
# now append and get out
revision.derivatives.append(new_derivative)
return
我怎樣才能運行此類型的查詢,選擇合適的revision
權owner
內並自動追加到內derivatives
收集上那revision
?
很難弄清楚如何開始使用像這樣的更新查詢。
你能提供一個實際的例子嗎?我不知道如何繼續。我會更新這個問題。 –
我知道_why_問題正在發生,我不知道如何實施解決方案。 –
除非您在應用程序端實施某種鎖定,否則無法使用保存並使其保持線程安全。另一種方法是切換到使用「更新」而不是「保存」 –