Skip to content

Commit 47825d9

Browse files
committed
PYTHON-697 - Fix upsert _id backward compatibility
1 parent f739025 commit 47825d9

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

pymongo/collection.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -554,6 +554,10 @@ def update(self, spec, document, upsert=False, manipulate=False,
554554
result['updatedExisting'] = True
555555
else:
556556
result['updatedExisting'] = False
557+
# MongoDB >= 2.6.0 returns the upsert _id in an array
558+
# element. Break it out for backward compatibility.
559+
if isinstance(result.get('upserted'), list):
560+
result['upserted'] = result['upserted'][0]['_id']
557561

558562
return result
559563

test/test_collection.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2224,6 +2224,20 @@ class ExtendedDict(dict):
22242224
as_class=ExtendedDict)
22252225
self.assertTrue(isinstance(result, ExtendedDict))
22262226

2227+
def test_update_backward_compat(self):
2228+
# MongoDB versions >= 2.6.0 don't return the updatedExisting field
2229+
# and return upsert _id in an array subdocument. This test should
2230+
# pass regardless of server version or type (mongod/s).
2231+
c = self.db.test
2232+
c.drop()
2233+
oid = ObjectId()
2234+
res = c.update({'_id': oid}, {'$set': {'a': 'a'}}, upsert=True)
2235+
self.assertFalse(res.get('updatedExisting'))
2236+
self.assertEqual(oid, res.get('upserted'))
2237+
2238+
res = c.update({'_id': oid}, {'$set': {'b': 'b'}})
2239+
self.assertTrue(res.get('updatedExisting'))
2240+
22272241
def test_find_and_modify_with_sort(self):
22282242
c = self.db.test
22292243
c.drop()

0 commit comments

Comments
 (0)