3 (supplement). The addition, deletion, modification and query of embedded documents by mongodb
Suppose all the documents in our collection are in this format:
{"_ id": ObjectId ("5c177b84f4e84940e0bd578d"), "name": "suhaozhi", "pwd": "suhaozhi", "phone": [{"phone_num": "13333333333", "type": "cmcc"}, {"phone_num": 1555555555, "type": "chinanet"}], "type": "chinanet"}
Now you need to search for records whose type subfield in the phone field has a value of CMCC:
Db.tmp.find ({phone: {$elemMatch: {cs: "cmcc"})
If you want to modify the type field corresponding to the phone_num of 13333333333 in the phone field of the above document, it is chinanet:
Db.tmp.update ({"name": "suhaozhi", "phone.phone_num": "13333333333"}, {$set: {"phone.$.cs": "chinanet"}})
If you want to embed the document, insert another piece of data:
Db.tmp.update ({"name": "suhaozhi"}, {$push: {"phone_num": "23333", "type": "cmcc"})
Delete a piece of data from the embedded document: