MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Array of objects with PyMongo

hi all,
how manage a array of object with pymongo ? I try with find-and_modify , updateone but it’s not right
do you have a exemple to insert a object into my array ou update it

many thanks

I’ve a collection

test :test
state : array
0 :
date : 22-03-2020 xxxx
user : test user
state : pending

1:
date : 22-03-2020 xxxx
user : test user2
state : pending2

how manage a array of object with pymongo ?

Here is an example, using a collection called as arrays with one document.

Initially I inserted a document from the mongo shell, and queried:

> db.arrays.findOne()
{
        "_id" : 1,
        "state" : [
                {
                        "date" : ISODate("2020-03-25T15:10:22.220Z"),
                        "user" : "user-1",
                        "state" : "pending"
                },
                {
                        "date" : ISODate("2020-03-26T09:57:17.315Z"),
                        "user" : "user-2",
                        "state" : "active"
                }
        ]
}

The array state will be updated to add a new object, then update this new object and finally delete the new object from the array.

The new object is:

{
     "date" : "today's date",
     "user" : "user-3",
     "state" : "none"
}

I used the Python shell to run the following code interactively using PyMongo 3.9 and MongoDB 4.2.

### Connect to MongoDB database and query the arrays collection:
###
>>> import pymongo
>>> from pymongo import MongoClient
>>> client = MongoClient()
>>> db = client.test
>>> collection = db.arrays
>>> import pprint
>>> pprint.pprint(collection.find_one())
{'_id': 1.0,
 'state': [{'date': datetime.datetime(2020, 3, 25, 15, 10, 22, 220000),
            'state': 'pending',
            'user': 'user-1'},
           {'date': datetime.datetime(2020, 3, 26, 9, 57, 17, 315000),
            'state': 'active',
            'user': 'user-2'}]}

###
### Add a new object to the 'state' array, using the '$push' array update operator.
### 'result' is a UpdateResult object.
###
>>> import datetime
>>> result = collection.update_one( { '_id': 1 }, 
                                    { '$push': { 'state': { 'date' : datetime.datetime.utcnow(),
                                                 'user' : 'user-3', 'state' : 'none'
                                     } } } )
>>> result.matched_count
1
>>> result.modified_count
1
>>> pprint.pprint(collection.find_one())
{'_id': 1.0,
 'state': [{'date': datetime.datetime(2020, 3, 25, 15, 10, 22, 220000),
            'state': 'pending',
            'user': 'user-1'},
           {'date': datetime.datetime(2020, 3, 26, 9, 57, 17, 315000),
            'state': 'active',
            'user': 'user-2'},
           {'date': datetime.datetime(2020, 3, 27, 10, 1, 28, 267000),
            'state': 'none',
            'user': 'user-3'}]}

###
### Update the new object in the 'state' array, using the '$set' update operator.
###
>>> result = collection.update_one( { '_id': 1, 'state.state': 'none' }, { '$set': { 'state.$.state' : 'done' } } )
>>> result.modified_count
1
>>> pprint.pprint(collection.find_one())
{'_id': 1.0,
 'state': [{'date': datetime.datetime(2020, 3, 25, 15, 10, 22, 220000),
            'state': 'pending',
            'user': 'user-1'},
           {'date': datetime.datetime(2020, 3, 26, 9, 57, 17, 315000),
            'state': 'active',
            'user': 'user-2'},
           {'date': datetime.datetime(2020, 3, 27, 10, 1, 28, 267000),
            'state': 'done',
            'user': 'user-3'}]}

###
### Remove the new object from the 'state' array, using the '$pull' array update 
operator.
###
>>> result = collection.update_one( { '_id': 1 }, { '$pull': { 'state' : { 'state': 'done' } } } )
>>> result.modified_count
1
>>> pprint.pprint(collection.find_one())
{'_id': 1.0,
 'state': [{'date': datetime.datetime(2020, 3, 25, 15, 10, 22, 220000),
            'state': 'pending',
            'user': 'user-1'},
           {'date': datetime.datetime(2020, 3, 26, 9, 57, 17, 315000),
            'state': 'active',
            'user': 'user-2'}]}
2 Likes

Thanks for the quick feedback and examples. I have successfully implemented the code in my project and it works.