cresendez744
cresendez744

Reputation: 91

How do I push an element into an array within an object in MongoDB database?

I'm new to MongoDB and I'm trying to figure out how to push an element into an array inside of an object. Here is the database:

{
    "_id": {
        "$oid": "605cee2f08588cb6263c33a4"
    },
    "userID": "9346",
    "firstName": "James",
    "sessionsLog": {
        "date": [],
        "timestamp": [],
        "duration": []
    }
},
    {
    "_id": {
        "$oid": "605cee825ef711180adbc141"
    },
    "userID": "4778",
    "firstName": "Rob",
    "sessionsLog": {
        "date": [],
        "timestamp": [],
        "duration": []
    }
}

I have a date that I want to push into Rob's 'date' array: 3/30/2021.

What is the operation to push this new date into the date array?

This is what I've tried:

import pymongo
myclient = pymongo.MongoClient("...")
mydb= myclient["myDatabase"]
users = mydb["Users"]

userID = '4778'
dateToPush = '3/30/2021'
allUsers = users.find({}, {'_id': 1, 'userID': 1, 'sessionsLog': 1})
for u in allUsers:
    if u.get('userID') == userID:
        users.update_one(
            {'userID': u.get('userID')},
            {'$push': {'sessionsLog'['date']: dateToPush}}
        )

Upvotes: 2

Views: 392

Answers (1)

https://docs.mongodb.com/manual/reference/operator/update/push/

Use . for nested objects in your query.

Change

'$push': {'sessionsLog'['date']: dateToPush}

to

'$push': {'sessionsLog.date': dateToPush}

Demo - https://mongoplayground.net/p/30GIvWkHDV1

db.collection.update({
  "userID": "9346"
},
{
  $push: {
    "sessionsLog.date": { a: 1, b: 2 }
  }
})

Upvotes: 4

Related Questions