如何在MongoDB中更新数组子文档的一部分

时间:2018-01-12 10:40:12

标签: mongodb simple-schema

我的mongodb集合中有这个文档:

{
  "_id": "YLRM9Wi7f6tp6qNbS",
  "sessionId": "hLDkkJKR4Muik6tbe",
  "userId": "ZYoG4cH8HcCDPMDGr",
  "shopId": "J8Bhq3uTtdgwZx3rz",
  "workflow": {
    "status": "",
    "workflow": ["String"]
  },
  "billing": [Object],
  "discount": 0,
  "tax": 0,
  "items": [
    {
      "_id": "JwR233jD2c4HKeYKq",
      "shopId": "J8Bhq3uTtdgwZx3rz",
      "productId": "BCTMZ6HTxFSppJESk",
      "quantity": 1,
      "product": {
        "_id": "BCTMZ6HTxFSppJESk",
        "title": "Product",
        "shopId": "J8Bhq3uTtdgwZx3rz",
        "ancestors": [],
        "createdAt": "2018-01-12T10:22:18.853Z",
        "description": "",
        "handle": "product",
        "hashtags": [
          "rpjCvTBGjhBi2xdro",
          "cseCBSSrJ3t8HQSNP"
        ],
        "price": {
          "range": "12.99 - 19.99",
          "min": 12.99,
          "max": 19.99
        },
        "isVisible": true,
        "isLowQuantity": false,
        "isSoldOut": false,
        "isBackorder": false,
        "metafields": [
          {
            "key": "Material",
            "value": "Cotton"
          },
          {
            "key": "Quality",
            "value": "Excellent"
          }
        ],
        "pageTitle": "",
        "type": "simple",
        "updatedAt": "2018-01-12T10:22:18.854Z",
        "vendor": "Vendor_Name",
        "originCountry": "country",
        "requiresShipping": true,
        "isDeleted": false,
        "template": "productDetailSimple",
        "workflow": {
          "status": "new"
        }
      },
      "variants": {},
      "title": "Product",
      "type": "simple",
      "parcel": {
        "weight": 25,
        "height": 3,
        "width": 10,
        "length": 10
      },
      "shippingMethod": {
        "shopId": "J8Bhq3uTtdgwZx3rz",
        "shipmentQuotes": [Object],
        "shipmentQuotesQueryStatus": {
          "requestStatus": "success",
          "numOfShippingMethodsFound": 11
        },
        "_id": "s3EJXrLsZe73RbLiD",
        "address": {},
        "shipmentMethod": {},
        "paymentId": "nyybR5BNvDDrJrtwe",
        "items": [
          {
            "_id": "JwR233jD2c4HKeYKq",
            "productId": "BCTMZ6HTxFSppJESk",
            "shopId": "J8Bhq3uTtdgwZx3rz",
            "variantId": "CJoRBm9vRrorc9mxZ"
          }
        ],
        "workflow": {
          "status": "new",
          "workflow": ["String"]
        }
      },
      "workflow": {
        "status": "new",
        "workflow": ["String"]
      }
    }
  ],
  "shipping": [Object],
  "email": "johndoe@mail.com",
  "cartId": "L6sSGv4NR9rpbDbsd",
  "createdAt": "2018-01-12T10:22:18.850Z"
}

字段items是一个对象数组,我想只更新对象的一部分,特别是workflow字段而不触及items数组中对象的其他部分。

我能够使用循环执行此操作,但它导致某些测试失败。使用循环是否有更好的做法?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用findAndModify方法。 遍历工作流程密钥广告尝试设置值。 希望这会有所帮助。