简体   繁体   中英

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}}
        )

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 }
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM