dongtuo3795 2019-02-02 07:02
浏览 167

如何更新文档中数组中的字段

I have a document with following structure. I want to insert a new file in the array files followed by making all other file status set to "INACTIVE". After inserting, I am trying following code to update other file of the array but it is unable to match.

{
  {
 "id":"fafsahjaf867rwhrbjw",
 "files" : [
            {"name": "123", status:"ACTIVE"},
            {"name": "124", status:"ACTIVE"},
            {"name": "125", status:"ACTIVE"},
            {"name": "126", status:"ACTIVE"},
           ] 
   },
}

    query = bson.M{ "id": productId,
    "files": bson.M{
        "$not": bson.M{"$elemMatch": fileObj}}}

    update = bson.M{
    "$set": bson.M{
        "files.$.status": "INACTIVE",
    },
  }
  • 写回答

1条回答 默认 最新

  • du656637962 2019-02-02 08:51
    关注

    If you have Mongo >= 3.6, here an example to edit all but the last with name 126.

    db.collection.update(
      { "id" : "fafsahjaf867rwhrbjw", "files.name": "126" },
      { "$set": { "files.$[elem].status": "INACTIVE" } },
      { "arrayFilters": [{ "elem.name": {$ne : "126"} }], "multi": true }
    )
    

    Got that solution from How to Update Multiple Array Elements in mongodb

    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择