In [1]:
import pymongo
In [ ]:
 
In [ ]:
 
In [2]:
client = pymongo.MongoClient("mongodb://192.168.31.151:27017")
In [5]:
[i for i in client["db"].list_collections()]
Out[5]:
[]
In [8]:
client["db"]["test"].create_index([("serial", pymongo.ASCENDING)], unique=True)
Out[8]:
'serial_1'
In [9]:
[i for i in client["db"].list_collections()]
Out[9]:
[{'name': 'test',
  'type': 'collection',
  'options': {},
  'info': {'readOnly': False,
   'uuid': UUID('97940838-8534-43d0-9143-afb3446d50c7')},
  'idIndex': {'v': 2, 'key': {'_id': 1}, 'name': '_id_', 'ns': 'db.test'}}]
In [ ]:
 
In [10]:
c = client["db"]["test"]
In [11]:
c.insert_one({
    "serial": 1,
    "a": 2
})
Out[11]:
<pymongo.results.InsertOneResult at 0x7fe67822a948>
In [12]:
[i for i in c.find()]
Out[12]:
[{'_id': ObjectId('5ef12868c17e1c340e6185b8'), 'serial': 1, 'a': 2}]
In [13]:
[i for i in c.find({}, {"_id": 0})]
Out[13]:
[{'serial': 1, 'a': 2}]
In [14]:
c.update_one({"serial": 2}, {
    "$set": {
        "serial": 2,
        "b": 3
    }
}, upsert=True)
Out[14]:
<pymongo.results.UpdateResult at 0x7fe66a3666c8>
In [15]:
[i for i in c.find({}, {"_id": 0})]
Out[15]:
[{'serial': 1, 'a': 2}, {'serial': 2, 'b': 3}]
In [16]:
c.update_one({"serial": 2}, {
    "$set": {
        "serial": 2,
        "b": 4
    }
}, upsert=True)
Out[16]:
<pymongo.results.UpdateResult at 0x7fe66a366c48>
In [17]:
[i for i in c.find({}, {"_id": 0})]
Out[17]:
[{'serial': 1, 'a': 2}, {'serial': 2, 'b': 4}]
In [ ]: