簡體   English   中英

更新數組 mongodb 內 object 內的字符串

[英]Update String inside object inside array mongodb

我有一個看起來像這樣的文檔

{

    "_id":{
        "$oid":"id"
    },
    "side1":[
        {
            "username":"test1",
            "id":"id1",
            
        },
        {
            "username":"test2",
            "id":"id2",
            
        },
        {
            "username":"test3",
            "id":"id3",
            
        }
       
    ],
    "side2":[
        {
            "username":"test4",
            "id":"id4",
            
        },
        {
            "username":"test5",
            "id":"id5",
            
        },
        {
            "username":"test6",
            "id":"id6",
            
        }
        
    ],


}

我希望能夠搜索和更新其中一側,例如,如果我使用用戶名搜索 side1 並且該用戶名將在那里,那么我將能夠使用此用戶名為 object 設置其他字段。 類似於: Search side1 username test1: $set result.id: "43242342"這會將用戶名為 test1 的 object 的 ID 設置為 43242342。我不確定 go 如何執行此操作,我嘗試使用$elemMatch 但這並沒有帶來任何結果。

Test.findOne({ id: id }, 
                
                { side1: { $elemMatch: {username: username} } }, function (err, result) {
                if (err) {
                    console.log(err);
                } else {
                    console.log(result)
                }
            });

我不太確定您想如何更新文檔,但也許這就是您要找的東西?

db.collection.update({
  "_id": ObjectId("000000000000000000000001"),
  "side1.username": "test1"
},
{
  "$set": {
    "side1.$.id": "43242342"
  }
})

mongoplayground.net上試用。

示例更新文檔:

[
  {
    "_id": ObjectId("000000000000000000000001"),
    "side1": [
      {
        "id": "43242342",
        "username": "test1"
      },
      {
        "id": "id2",
        "username": "test2"
      },
      {
        "id": "id3",
        "username": "test3"
      }
    ],
    "side2": [
      {
        "id": "id4",
        "username": "test4"
      },
      {
        "id": "id5",
        "username": "test5"
      },
      {
        "id": "id6",
        "username": "test6"
      }
    ]
  }
]

你能做這樣的事情嗎?

function addProperty(id, side, username, property, value) {
  const query = {
    _id: {
      $oid: id,
    },
  };

  const update = {
    $push: {
      [side]: {
        username: username,
        [property]: value,
      },
    },
  };

  const options = {
    upsert: true,
  };

  db.collection("Test").updateOne(query, update, options);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM