简体   繁体   中英

mongoDB remove sub-array

Ok is there a quick way to remove the follwoing though PHP mongodb

here is our mongoDB row

{
  "today":""
  "session": "6266262626",
  "products": [
    {
      "barcode": "27788822",
      "item": "village day ticket",
      "price": 1315,
      "qty": "3"
    },
    {
      "barcode": "8544122",
      "item": "village night ticket",
      "price": 1433,
      "qty": "1"
    }
  ]
}

I would like to delete the product

{
      "barcode": "8544122",
      "item": "village night ticket",
      "price": 1433,
      "qty": "1"
}

I know how to update, and insert but cant figure out how to delete it.

here is a mongo command to delete the item, given its barcode :

db.collection.update({session:'6266262626'},{ $pull: { products: { barcode : '8544122' } }})

If you want to delete multiple items from the products array, given an array of barcodes :

db.collection.update({session:'6266262626'},{ $pull: { products: { barcode : {$in : ['27788822','8544122'] } } }})

I don't know the PHP equivalent of those commands, but here is a related question using $pull and PHP which may help :

MongoDB pull array element from a collection

this question is pretty old, but deleting multiple array items in a single query was giving me trouble today, and in my case the above is working out, so maybe it will help somebody else, thanks.

Reading the docs is your friend. Use the positional operator

http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

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