Update field in exact element array in MongoDB

后端 未结 3 792
执念已碎
执念已碎 2020-11-22 07:19

I have a document structured like this:

{
    _id:\"43434\",
    heroes : [
        { nickname : \"test\",  items : [\"\", \"\", \"\"] },
        { nickname          


        
相关标签:
3条回答
  • 2020-11-22 07:34

    You need to make use of 2 concepts: mongodb's positional operator and simply using the numeric index for the entry you want to update.

    The positional operator allows you to use a condition like this:

    {"heroes.nickname": "test"}
    

    and then reference the found array entry like so:

    {"heroes.$  // <- the dollar represents the first matching array key index
    

    As you want to update the 2nd array entry in "items", and array keys are 0 indexed - that's the key 1.

    So:

    > db.denis.insert({_id:"43434", heroes : [{ nickname : "test",  items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]});
    > db.denis.update(
        {"heroes.nickname": "test"}, 
        {$set: {
            "heroes.$.items.1": "new_value"
        }}
    )
    > db.denis.find()
    {
        "_id" : "43434", 
        "heroes" : [
            {"nickname" : "test", "items" : ["", "new_value", "" ]},
            {"nickname" : "test2", "items" : ["", "", "" ]}
        ]
    }
    
    0 讨论(0)
  • 2020-11-22 07:54
    db.collection.update(
    {
    heroes:{$elemMatch:{ "nickname" : "test"}}},
     {
         $push: {
            'heroes.$.items': {
               $each: ["new_value" ],
               $position: 1
            }
         }
       }
    
    )
    
    0 讨论(0)
  • 2020-11-22 08:00

    This solution works well. Just want to add one point. Here is the structure. I need to find OrderItemId is 'yyy' and update. If the query field in condition is an array, like below "OrderItems.OrderItemId" is array. You can not use "OrderItems.OrderItemId[0]" as operation in the query. Instead, you need to use "OrderItems.OrderItemId" to compare. Otherwise, it can not match one.

    {
      _id: 'orderid',
      OrderItems: [
       {
         OrderItemId: ['xxxx'], 
        ... },
       {
         OrderItemId: ['yyyy'], 
        ...}, 
    ]
    
    }
    
     result =  await collection.updateOne(
            { _id: orderId, "OrderItems.OrderItemId": [orderItemId] },
            { $set: { "OrderItems.$.imgUrl": imgUrl[0], "OrderItems.$.category": category } },
            { upsert: false },
          )
        console.log('  (result.modifiedCount) ', result.modifiedCount)
        console.log('  (result.matchedCount) ', result.matchedCount)
    
    0 讨论(0)
提交回复
热议问题