0

In mongoDB collection I have different field types. Is it possible update doc in this collection with update_one method?

doc = {"upd_time": datetime.datetime.now(), "categories": [1,2,3]}
mng_collection.update_one({"_id": id}, {"$set": doc}, upsert=True)

That code replace existing array in categories field, but I need to add values from doc["categories"] array if not existing in collection doc array.

1 Answers1

1

You need to use $push with $each to add elements to the existing array. $set will always replace existing value with new one.

You can try this:

doc = {"upd_time": datetime.datetime.now(), "categories": [1,2,3]}
mng_collection.update_one({"_id": id}, {
    "$set": { "doc.upd_time" : doc.upd_time},
    $push : {categories : {$each : doc.categories}}
}, upsert=True)

Read more about $push documentation, and how to use it with $each here.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52