简体   繁体   中英

PyMongo: Is there a way to add data to a existing document in MongoDB using python?

I have a database 'Product'. Which contains a collection name 'ProductLog'. Inside this collection, there are 2 documents in the following format:

  {
    "environment": "DevA",
    "data": [
      {
        "Name": "ABC",
        "Stream": "Yes"
      },
      {
        "Name": "ZYX",
        "Stream": "Yes"
      }
    ]
  },
  {
    "environment": "DevB",
    "data": [
      {
        "Name": "ABC",
        "Stream": "Yes"
      },
      {
        "Name": "ZYX",
        "Stream": "Yes"
      }
    ]
  }

This gets added as 2 documents in collection. I want to append more data in the already existing document's 'data' field in MongoDB using python. Is there a way for that? I guess update would remove the existing fields in "data" field or may update a whole document.

For example: Adding one more array in EmployeeDetails field, while the earlier data in EmployeeDetail also remains.

在此处输入图像描述

I want to show how you can append more data in the already existing document 'data' field in MongoDB using python:

First install pymongo:

pip install mongoengine

Now let's get our hands dirty:

from pymongo import MongoClient

mongo_uri = "mongodb://user:pass@mongosrv:27017/"
client = MongoClient(mongo_uri)
database = client["Product"]
collection = "ProductLog"

database[collection].update_one({"environment": "DevB"}, {
    "$push": {
        "data": {"Name": "DEF", "Stream": "NO"}
    }
})

There is a SQL library in Python language through which you can insert/add your data in your desired database. For more information, check out the tutorial

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