简体   繁体   中英

MongoDB. How to move a field from one subdocument to other in an array?

I have a collection like this.

{ "key_a": 1,
  "key_b": [
           {"name": "pepe"},
           {"name": "juan", "code": 12345},
           {"name": "luis", "code": 5678}
          ]
}

"key_b" is an array of documents. I want to find documents that contains "pepe" and "juan", anf then move "code" from "juan" to "pepe". The result will be:

{ "key_a": 1,
  "key_b": [
           {"name": "pepe", "code": 12345},
           {"name": "juan"},
           {"name": "luis", "code": 5678}
          ]
}

What is the best way to do it? I am using pymongo.

I'd do this in 2 steps. It's not strictly moving the field rather than updating both documents.

In MongoDB you can use $unset to remove a field: https://docs.mongodb.com/manual/reference/operator/update/unset/

findOneAndUpdate({ name: "juan"}, { $unset: { "code": "" }}, { upsert: true }).exec()

Then you could use eg

findOneAndUpdate({ name: "pepe"}, { "code": newValue }, { upsert: true}).exec()

(The examples are mongoose, Pymongo update syntax is here: https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_update , not sure about $unset in Pymongo)

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