简体   繁体   English

如何在pymongo中删除嵌套文档

[英]How to delete a nested document in pymongo

I am working on a product development DB. 我正在研究产品开发DB。 Each product consists of several items and services. 每个产品包含多个项目和服务。 Each item has several properties, and I have an item collection. 每个项目都有几个属性,我有一个项目集合。 So I have many to many relationships. 所以我有很多很多关系。

I want to delete an item inside a product. 我想删除产品中的项目。

I have tried $pull , with update but I haven't got any luck. 我试过$pull ,有更新,但我没有运气。 As I understand I need to find the document first and then delete the nested document with a $pull . 据我所知,我需要先找到文档,然后用$pull删除嵌套文档。

This is my flash route with the update: 这是我更新的闪存路线:

main.route("/Producto/<string:prd_id>/<string:itm_id>/Borrar" , methods= ['GET','POST'])
@login_required
def borraprditm(prd_id,itm_id):
if request.method == 'POST':
    productos.update_one({'comp':usuario['comp_id'],"prd:id":prd_id},{ "$pull": {"items.itm_id":  {"itm_id": itm_id}}})
    flash('El Elemento ha sido eliminado', 'danger')
    return redirect(url_for('main.producto'))
return render_template('prditmdelete.html')

This is my Document: 这是我的文件:

_id  : 5cf572fc341026b937931734
comp : 13847
codigo : "prueba"
descripcion : "prueba 2"
um : "Prd"
cantidad : 0
precio : 0
prd_id : "0344131"
items :Array 

  0 : Object
  _id : 5cf18a08cf6ea6c98dd7861e
  comp : 13847
  codigo : "750-881"
  descripcion : "PFC 1Mb, CoDeSyS 2.3 - Mca WAGO"
  um : "Pza"
  precio : 1234
  itm_id : "0645566"

  1 : Object
  _id : 5cf18a13cf6ea6c98dd7861f
  comp : 13847
  codigo : "750-8202"
  descripcion : "PFC-200 Linux"
  um : "Pza"
  precio : 3453
  itm_id : "0915059"

  2 : Object
  _id : 5cf18a20cf6ea6c98dd78620
  comp : 13847
  codigo : "jack"
  descripcion : "tapa belden nodo"
  um : "Pza"
  precio : 20
  itm_id : "0918133"

You need to tell $pull which array to pull from, and then how to find the sub-document to pull: 你需要告诉$pull哪个数组,然后如何找到要拉的子文档:

{"$pull": {"items": {"itm_id": itm_id}}}

This means: 这意味着:

  • for each document matching the query, 对于与查询匹配的每个文档,
  • pull from the "items" array 拉出“items”数组
  • any sub-documents that match the sub-query {"itm_id": itm_id} 与子查询匹配的任何子文档{"itm_id": itm_id}

See more details and examples on the MongoDB documentation 查看有关MongoDB文档的更多详细信息和示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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